<commit_before># -*- coding: utf-8 -*-
from qtpy import QtCore, QtGui, QtWidgets
import pyqtgraph as pg
import os, time
import numpy as np
from skimage import measure
from .tracefig import TraceFig
from . import global_vars as g
from .process.measure import measure
from .roi import *
from .utils.misc import save_file_gui
pg.setConfigOptions(useWeave=False)

class ImageView(pg.ImageView):
    def __init__(self, *args, **kargs):
        pg.ImageView.__init__(self, *args, **kargs)
        self.view.unregister()
        self.view.removeItem(self.roi)
        self.view.removeItem(self.normRoi)
        self.roi.setParent(None)
        self.normRoi.setParent(None)
        self.ui.menuBtn.setParent(None)
        self.ui.roiBtn.setParent(None) # gets rid of 'roi' button that comes with ImageView
        self.ui.normLUTbtn = QtWidgets.QPushButton(self.ui.layoutWidget)
        self.ui.normLUTbtn.setObjectName("LUT norm")
        self.ui.normLUTbtn.setText("LUT norm")
        self.ui.gridLayout.addWidget(self.ui.normLUTbtn, 1, 1, 1, 1)

        self.ui.roiPlot.setMaximumHeight(40)
        self.ui.roiPlot.getPlotItem().getViewBox().setMouseEnabled(False)
        self.ui.roiPlot.getPlotItem().hideButtons()

    def hasTimeAxis(self):
        return 't' in self.axes and not (self.axes['t'] is None or self.image.shape[self.axes['t']] == 1)

    def roiClicked(self):
        showRoiPlot = False
        if self.hasTimeAxis():
            showRoiPlot = True
            mn = self.tVals.min()
            mx = self.tVals.max() + .01
            self.ui.roiPlot.setXRange(mn, mx, padding=0.01)
            self.timeLine.show()
            self.timeLine.setBounds([mn, mx])
            self.ui.roiPlot.show()
            if not self.ui.roiBtn.isChecked():
                self.ui.splitter.setSizes([self.height()-35, 35])
        else:
            self.timeLine.hide()
            #self.ui.roiPlot.hide()
            
        self.ui.roiPlot.setVisible(showRoiPlot)

class Window(QtWidgets.QWidget):
    """
    Window objects are the central objects in flika. Almost all functions in the 
    :mod:`process <flika.process>` module are performed on Window objects and 
    output Window objects. 

    Args:
        tif (numpy.array): The image the window will store and display
        name (str): The name of the window.
        filename (str): The filename (including full path) of file this window's image orinated from.
        commands (list of str): a list of the commands used to create this window, starting with loading the file.
        metadata (dict): dict: a dictionary containing the original file's metadata.


    """
    closeSignal = QtCore.Signal()
    keyPressSignal = QtCore.Signal(QtCore.QEvent)
    sigTimeChanged = QtCore.Signal(int)
    gainedFocusSignal = QtCore.Signal()
    lostFocusSignal = QtCore.Signal()

    def __init__(self, tif, name='flika', filename='', commands=[], metadata=dict()):
        QtWidgets.QWidget.__init__(self)
        self.name = name  #: str: The name of the window.
        self.filename = filename  #: str: The filename (including full path) of file this window's image orinated from.
        self.commands = commands  #: list of str: a list of the commands used to create this window, starting with loading the file.
        self.metadata = metadata  #: dict: a dictionary containing the original file's metadata.
        self.volume = None  # When attaching a 4D array to this Window object, where self.image is a 3D slice of this volume, attach it here. This will remain None for all 3D Windows
        self.scatterPlot = None
        self.closed = False  #: bool: True if the window has been closed, False otherwise.
        self.mx = 0  #: int: The number of pixels wide the image is in the x (left to right) dimension.
        self.my = 0  #: int: The number of pixels heigh the image is in the y (up to down) dimension.
        self.mt = 0  #: int: The number of frames in the image stack.
        self.image = tif
        self.dtype = tif.dtype  #: dtype: The datatype of the stored image, e.g. ``uint8``.
        self.top_left_label = None
        self.rois = []  #: list of ROIs: a list of all the :class:`ROIs <flika.roi.ROI_Base>` inside this window.
        self.currentROI = None  #: :class:`ROI <flika.roi.ROI_Base>`: When an ROI is clicked, it becomes the currentROI of that window and can be accessed via this variable.
        self.creatingROI = False
        self.imageview = None
        self.currentIndex = 0
        self.linkedWindows = set()
        self.measure = measure
        self.resizeEvent = self.onResize
        self.moveEvent = self.onMove
        self.pasteAct = QtWidgets.QAction("&Paste", self, triggered=self.paste)
        self.sigTimeChanged.connect(self.showFrame)
        self._check_for_infinities(tif)
        self._init_dimensions(tif)
        self._init_imageview(tif)
        self.setWindowTitle(name)
        self.normLUT(tif)
        self._init_scatterplot()
        self._init_menu()
        self._init_geometry()
        self.setAsCurrentWindow()

    def _init_geometry(self):
        assert g.currentWindow != self  # self.setAsCurrentWindow() must be called after this function
        if g.currentWindow is None:
            if 'window_settings' not in g.settings:
                g.settings['window_settings'] = dict()
            if 'coords' in g.settings['window_settings']:
                geometry = QtCore.QRect(*g.settings['window_settings']['coords'])
            else:
                width = 684
                height = 585
                nwindows = len(g.windows)
                x = 10 + 10 * nwindows
                y = 300 + 10 * nwindows
                geometry = QtCore.QRect(x, y, width, height)
                g.settings['window_settings']['coords'] = geometry.getRect()
        else:
            geometry = g.currentWindow.geometry()

        desktopGeom = QtWidgets.QDesktopWidget().geometry()

        maxX = (desktopGeom.width() - geometry.width()) or 1
        maxY = (desktopGeom.height() - geometry.height()) or 1
        newX = (geometry.x() + 10) % maxX
        newY = (geometry.y() + 10) % maxY
        if desktopGeom.x() < 0:
            newX += desktopGeom.x()
        
        print(newX, newY)
        geometry = QtCore.QRect(newX, newY, geometry.width(), geometry.height())
        self.setGeometry(geometry)
        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.addWidget(self.imageview)
        self.layout.setContentsMargins(0, 0, 0, 0)
        if g.settings['show_windows']:
            self.show()
            self.raise_()
            QtWidgets.qApp.processEvents()

    def _check_for_infinities(self, tif):
        try:
            if np.any(np.isinf(tif)):
                tif[np.isinf(tif)] = 0
                g.alert('Some array values were inf. Setting those values to 0')
        except MemoryError:
            pass

    def _init_imageview(self, tif):
        self.imageview = ImageView(self)
        self.imageview.setMouseTracking(True)
        self.imageview.installEventFilter(self)
        self.imageview.ui.normLUTbtn.pressed.connect(lambda : self.normLUT(self.image))
        rp = self.imageview.ui.roiPlot.getPlotItem()
        self.linkMenu = QtWidgets.QMenu("Link frame")<commit_msg>remove print statement<commit_after># -*- coding: utf-8 -*-
from qtpy import QtCore, QtGui, QtWidgets
import pyqtgraph as pg
import os, time
import numpy as np
from skimage import measure
from .tracefig import TraceFig
from . import global_vars as g
from .process.measure import measure
from .roi import *
from .utils.misc import save_file_gui
pg.setConfigOptions(useWeave=False)

class ImageView(pg.ImageView):
    def __init__(self, *args, **kargs):
        pg.ImageView.__init__(self, *args, **kargs)
        self.view.unregister()
        self.view.removeItem(self.roi)
        self.view.removeItem(self.normRoi)
        self.roi.setParent(None)
        self.normRoi.setParent(None)
        self.ui.menuBtn.setParent(None)
        self.ui.roiBtn.setParent(None) # gets rid of 'roi' button that comes with ImageView
        self.ui.normLUTbtn = QtWidgets.QPushButton(self.ui.layoutWidget)
        self.ui.normLUTbtn.setObjectName("LUT norm")
        self.ui.normLUTbtn.setText("LUT norm")
        self.ui.gridLayout.addWidget(self.ui.normLUTbtn, 1, 1, 1, 1)

        self.ui.roiPlot.setMaximumHeight(40)
        self.ui.roiPlot.getPlotItem().getViewBox().setMouseEnabled(False)
        self.ui.roiPlot.getPlotItem().hideButtons()

    def hasTimeAxis(self):
        return 't' in self.axes and not (self.axes['t'] is None or self.image.shape[self.axes['t']] == 1)

    def roiClicked(self):
        showRoiPlot = False
        if self.hasTimeAxis():
            showRoiPlot = True
            mn = self.tVals.min()
            mx = self.tVals.max() + .01
            self.ui.roiPlot.setXRange(mn, mx, padding=0.01)
            self.timeLine.show()
            self.timeLine.setBounds([mn, mx])
            self.ui.roiPlot.show()
            if not self.ui.roiBtn.isChecked():
                self.ui.splitter.setSizes([self.height()-35, 35])
        else:
            self.timeLine.hide()
            #self.ui.roiPlot.hide()
            
        self.ui.roiPlot.setVisible(showRoiPlot)

class Window(QtWidgets.QWidget):
    """
    Window objects are the central objects in flika. Almost all functions in the 
    :mod:`process <flika.process>` module are performed on Window objects and 
    output Window objects. 

    Args:
        tif (numpy.array): The image the window will store and display
        name (str): The name of the window.
        filename (str): The filename (including full path) of file this window's image orinated from.
        commands (list of str): a list of the commands used to create this window, starting with loading the file.
        metadata (dict): dict: a dictionary containing the original file's metadata.


    """
    closeSignal = QtCore.Signal()
    keyPressSignal = QtCore.Signal(QtCore.QEvent)
    sigTimeChanged = QtCore.Signal(int)
    gainedFocusSignal = QtCore.Signal()
    lostFocusSignal = QtCore.Signal()

    def __init__(self, tif, name='flika', filename='', commands=[], metadata=dict()):
        QtWidgets.QWidget.__init__(self)
        self.name = name  #: str: The name of the window.
        self.filename = filename  #: str: The filename (including full path) of file this window's image orinated from.
        self.commands = commands  #: list of str: a list of the commands used to create this window, starting with loading the file.
        self.metadata = metadata  #: dict: a dictionary containing the original file's metadata.
        self.volume = None  # When attaching a 4D array to this Window object, where self.image is a 3D slice of this volume, attach it here. This will remain None for all 3D Windows
        self.scatterPlot = None
        self.closed = False  #: bool: True if the window has been closed, False otherwise.
        self.mx = 0  #: int: The number of pixels wide the image is in the x (left to right) dimension.
        self.my = 0  #: int: The number of pixels heigh the image is in the y (up to down) dimension.
        self.mt = 0  #: int: The number of frames in the image stack.
        self.image = tif
        self.dtype = tif.dtype  #: dtype: The datatype of the stored image, e.g. ``uint8``.
        self.top_left_label = None
        self.rois = []  #: list of ROIs: a list of all the :class:`ROIs <flika.roi.ROI_Base>` inside this window.
        self.currentROI = None  #: :class:`ROI <flika.roi.ROI_Base>`: When an ROI is clicked, it becomes the currentROI of that window and can be accessed via this variable.
        self.creatingROI = False
        self.imageview = None
        self.currentIndex = 0
        self.linkedWindows = set()
        self.measure = measure
        self.resizeEvent = self.onResize
        self.moveEvent = self.onMove
        self.pasteAct = QtWidgets.QAction("&Paste", self, triggered=self.paste)
        self.sigTimeChanged.connect(self.showFrame)
        self._check_for_infinities(tif)
        self._init_dimensions(tif)
        self._init_imageview(tif)
        self.setWindowTitle(name)
        self.normLUT(tif)
        self._init_scatterplot()
        self._init_menu()
        self._init_geometry()
        self.setAsCurrentWindow()

    def _init_geometry(self):
        assert g.currentWindow != self  # self.setAsCurrentWindow() must be called after this function
        if g.currentWindow is None:
            if 'window_settings' not in g.settings:
                g.settings['window_settings'] = dict()
            if 'coords' in g.settings['window_settings']:
                geometry = QtCore.QRect(*g.settings['window_settings']['coords'])
            else:
                width = 684
                height = 585
                nwindows = len(g.windows)
                x = 10 + 10 * nwindows
                y = 300 + 10 * nwindows
                geometry = QtCore.QRect(x, y, width, height)
                g.settings['window_settings']['coords'] = geometry.getRect()
        else:
            geometry = g.currentWindow.geometry()

        desktopGeom = QtWidgets.QDesktopWidget().geometry()

        maxX = (desktopGeom.width() - geometry.width()) or 1
        maxY = (desktopGeom.height() - geometry.height()) or 1
        newX = (geometry.x() + 10) % maxX
        newY = (geometry.y() + 10) % maxY
        if desktopGeom.x() < 0:
            newX += desktopGeom.x()
        
        geometry = QtCore.QRect(newX, newY, geometry.width(), geometry.height())
        self.setGeometry(geometry)
        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.addWidget(self.imageview)
        self.layout.setContentsMargins(0, 0, 0, 0)
        if g.settings['show_windows']:
            self.show()
            self.raise_()
            QtWidgets.qApp.processEvents()

    def _check_for_infinities(self, tif):
        try:
            if np.any(np.isinf(tif)):
                tif[np.isinf(tif)] = 0
                g.alert('Some array values were inf. Setting those values to 0')
        except MemoryError:
            pass

    def _init_imageview(self, tif):
        self.imageview = ImageView(self)
        self.imageview.setMouseTracking(True)
        self.imageview.installEventFilter(self)
        self.imageview.ui.normLUTbtn.pressed.connect(lambda : self.normLUT(self.image))
        rp = self.imageview.ui.roiPlot.getPlotItem()
        self.linkMenu = QtWidgets.QMenu("Link frame")
{'fraction_non_alphanumeric': 0.10571566132471284, 'fraction_numerical': 0.0072907352637733, 'mean_word_length': 2.3979901846225755, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6224458', 'n_tokens_mistral': 4545, 'n_tokens_neox': 4310, 'n_words': 1183}