예제 #1
0
    def test_click_help(self):
        """
        Test that help HtmlFrame is created
        """
        menus = self.frame.MenuBar.Menus
        fmenu, fmenu_name = menus[0]

        # once you have the correct menu
        help_id = fmenu.FindItem('Help')
        help_item = fmenu.FindItemById(help_id)

        top_windows = wx.GetTopLevelWindows()
        print('before')
        for window in top_windows:
            print('top-level window:', window)
            print('name:', window.Label)
        print('after')
        event = wx.CommandEvent(wx.EVT_MENU.evtType[0], help_id)
        self.frame.GetEventHandler().ProcessEvent(event)
        top_windows = wx.GetTopLevelWindows()
        help_window = False
        for window in top_windows:
            print('top-level window:', window)
            print('name:', window.Label)
            if window.Label == 'Help Window':
                help_window = window
        self.assertTrue(help_window)
        self.assertTrue(help_window.IsEnabled())
        file_name = os.path.split(help_window.page)[1]
        self.assertEqual('magic_gui.html', file_name)
        self.assertTrue(isinstance(help_window, pmag_widgets.HtmlFrame))
예제 #2
0
    def Run(self):
        global delete_before_connect
        #self.pcb = GetBoard()
        # net_name = "GND"
        pcb = pcbnew.GetBoard()

        #from https://github.com/MitjaNemec/Kicad_action_plugins
        #hack wxFormBuilder py2/py3
        try:
            _pcbnew_frame = [
                x for x in wx.GetTopLevelWindows()
                if x.GetTitle().lower().startswith('pcbnew')
            ][0]
        except:
            _pcbnew_frame = [
                x for x in wx.GetTopLevelWindows()
                if 'pcbnew' in wx._windows.Frame.GetTitle(x).lower()
            ][0]
        #aParameters = RoundTrackDlg(None)
        aParameters = RoundTrack_Dlg(_pcbnew_frame)
        if hasattr(pcb, 'm_Uuid'):
            aParameters.m_buttonDelete.Disable()
            aParameters.m_checkBoxDelete.Disable()
        #aParameters = RoundTrack_DlgEx(_pcbnew_frame)
        aParameters.Show()
        #end hack
        aParameters.m_distanceMM.SetValue("5")
        aParameters.m_segments.SetValue("16")
        aParameters.m_bitmap1.SetBitmap(
            wx.Bitmap(
                os.path.join(os.path.dirname(os.path.realpath(__file__)),
                             "round_track_help.png")))
        modal_result = aParameters.ShowModal()
        segments = self.CheckSegmentsInput(aParameters.m_segments.GetValue(),
                                           "number of segments")
        distI = FromMM(
            self.CheckDistanceInput(aParameters.m_distanceMM.GetValue(),
                                    "distance from intersection"))
        if aParameters.m_checkBoxDelete.IsChecked():
            delete_before_connect = True
        else:
            delete_before_connect = False
        if segments is not None and distI is not None:
            if modal_result == wx.ID_OK:
                Round_Selection(pcb, distI, segments)
                pcbnew.Refresh()
            elif modal_result == wx.ID_DELETE:
                Delete_Segments(pcb)
                #wx.LogMessage('Round Segments on Track Net Deleted')
            elif modal_result == wx.ID_REVERT:
                wxLogDebug('Connecting Tracks', debug)
                Connect_Segments(pcb)
            else:
                None  # Cancel
            #pcbnew.Refresh()
        else:
            None  # Invalid input
        aParameters.Destroy()
예제 #3
0
    def onClose(self, event):
        """
            Closes ODMTools Python
            Closes AUI Manager then closes MainWindow
        """

        #check to see if a script has been created
        if self.scriptcreate:
            msg = wx.MessageDialog(
                None, 'Would you like to save your editing script?',
                'Save Script', wx.YES_NO | wx.ICON_QUESTION)
            value = msg.ShowModal()
            if value == wx.ID_YES:
                self.txtPythonScript.OnSaveAs(event)

        # deinitialize the frame manager
        self.pnlPlot.Close()
        try:
            f = open(
                os.path.join(user_config_dir("ODMTools", "UCHIC"),
                             'ODMTools.config'), 'w')
            f.write(self._mgr.SavePerspective())
        except:
            print "error saving docking data"
        self._mgr.UnInit()

        # Shut down processes running in background
        if self.taskserver.numprocesses > 0 and self.taskserver.anyAlive:
            busy = wx.BusyInfo("Closing ODMTools ...", parent=self)

            # Terminate the processes
            self.taskserver.processTerminate()

        # IMPORTANT! if wx.TaskBarIcons exist, it will keep mainloop running

        windowsRemaining = len(wx.GetTopLevelWindows())
        if windowsRemaining > 0:
            import wx.lib.agw.aui.framemanager as aui
            # logger.debug("Windows left to close: %d" % windowsRemaining)
            for item in wx.GetTopLevelWindows():
                # logger.debug("Windows %s" % item)
                if not isinstance(item, self.__class__):
                    if isinstance(item, aui.AuiFloatingFrame):
                        item.Destroy()
                    elif isinstance(item, aui.AuiSingleDockingGuide):
                        item.Destroy()
                    elif isinstance(item, aui.AuiDockingHintWindow):
                        item.Destroy()
                    elif isinstance(item, wx.Dialog):
                        item.Destroy()
                    item.Close()
        logger.info("Closing ODMTools\n")
        self.Destroy()

        wx.GetApp().ExitMainLoop()
예제 #4
0
async def check_for_updates(show_result=False):
    if variables.update_in_progress:
        err = wx.MessageDialog(wx.GetTopLevelWindows()[0],
                               caption="UtopiaForReddit Updater",
                               message="Updater already in progress.")
        err.ShowModal()
        err.Destroy()
        return
    logging.info("Initializing updater.")
    updater_client = JustUpdateClient(ClientConfig(), variables.version,
                                      variables.config.get("update_channel"))
    if updater_client.is_post_update():
        logging.info("Running post update actions")
        updater_client.cleanup()
        updater_client.post_update_cleanup()
        return
    if variables.config.get("auto_check_for_updates") == False:
        return
    try:
        bypass_cache = False
        if variables.release_channel == "alpha":
            logging.debug(
                "Disabling cache when checking for updates on the alpha channel."
            )
            bypass_cache = True
        if updater_client.update_available(bypass_cache):
            variables.update_in_progress = True
            logging.debug("Update found.")
            logging.debug("Asking user to update.")
            q = wx.MessageDialog(
                wx.GetTopLevelWindows()[0],
                "You are running version {} however version {} is available. Do you want to update UtopiaForReddit now?"
                .format(
                    Version(variables.version).to_human_readable(),
                    updater_client._update_version.to_human_readable()),
                "UtopiaForReddit Updater",
                wx.YES_NO | wx.YES_DEFAULT | wx.STAY_ON_TOP)
            q.ShowModal()
            q.Destroy()
            if result == wx.ID_NO:
                variables.update_in_progress = False
                return
            # user wants to update.
            await _do_update(updater_client)
            return
        else:
            raise ValueError("No update available.")
    except (requests.exceptions.ConnectionError, ValueError, zlib.error) as e:
        logging.warn("Status when checking for updates: " + str(e))
        if show_result:
            result = wx.MessageDialog(wx.GetTopLevelWindows()[0],
                                      caption="UtopiaForReddit",
                                      message="No update found.")
            result.ShowModal()
            result.Destroy()
예제 #5
0
파일: test_dialog.py 프로젝트: ifwe/wxpy
def test_dialog_contextmanager():
    return
    n = len(wx.GetTopLevelWindows())
    with wx.Dialog(None, -1, 'test') as diag:
        diag.Bind(wx.EVT_SHOW, lambda e: wx.CallAfter(diag.Close)
                  if e.GetShow() else None)
        diag.ShowModal()

    wx.GetApp().ProcessIdle()
    assert n == len(wx.GetTopLevelWindows()), repr(
        (n, len(wx.GetTopLevelWindows())))
    def _HideOtherWindows(self):

        for tlw in wx.GetTopLevelWindows():

            if tlw == self:

                continue

            if not isinstance(tlw, (ClientGUITopLevelWindows.Frame,
                                    ClientGUITopLevelWindows.NewDialog)):

                continue

            if ClientGUIFunctions.IsWXAncestor(self, tlw, through_tlws=True):

                continue

            from . import ClientGUI

            if isinstance(tlw, ClientGUI.FrameGUI):

                continue

            if not tlw.IsShown() or tlw.IsIconized():

                continue

            tlw.Hide()

            self._windows_hidden.append(tlw)
예제 #7
0
 def test_something(self):
     wins = wx.GetTopLevelWindows()
     for win in wins:
         if win.GetTitle() == 'Test UI':
             break
     else:
         raise RuntimeError("The main window didn't show.")
예제 #8
0
def get_output_frame():
    print('-I- Fetching output frame')
    wins = wx.GetTopLevelWindows()
    for win in wins:
        if win.Name == 'frame':
            return win
    return False
예제 #9
0
    def Run(self):
        self.Initialize()

        pcbFrame = [
            x for x in wx.GetTopLevelWindows() if x.GetName() == 'PcbFrame'
        ][0]

        dlg = KeyAutoPlaceDialog(pcbFrame, 'Title', 'Caption')
        if dlg.ShowModal() == wx.ID_OK:
            templatePath = dlg.GetTemplatePath()
            if templatePath:
                templateCopier = TemplateCopier(self.logger, self.board,
                                                templatePath, dlg.IsTracks())
                templateCopier.Run()

            layoutPath = dlg.GetLayoutPath()
            if layoutPath:
                with open(layoutPath, "r") as f:
                    textInput = f.read()
                layout = json.loads(textInput)
                self.logger.info("User layout: {}".format(layout))
                placer = KeyPlacer(self.logger, self.board, layout)
                placer.Run(dlg.GetKeyAnnotationFormat(),
                           dlg.GetStabilizerAnnotationFormat(),
                           dlg.GetDiodeAnnotationFormat(), dlg.IsTracks())

        dlg.Destroy()
        logging.shutdown()
예제 #10
0
    def paint(e):
        dc = wx.AutoBufferedPaintDC(f)
        dc.Brush = wx.WHITE_BRUSH
        dc.Pen = wx.TRANSPARENT_PEN
        dc.DrawRectangleRect(f.ClientRect)
        font = f.Font
        font.PointSize = 12
        dc.Font = font

        x = y = 10
        found_rotater = False

        for win in wx.GetTopLevelWindows():
            try:
                rotater = win._ad_rotater
            except AttributeError:
                pass
            else:
                found_rotater = True
                dc.DrawText('%s: %r' % (win.Title, rotater), x, y)
                y += 20

        if not found_rotater:
            import gui.imwin.imwin_ads as imwin_ads
            secs = imwin_ads.secs_since_last_close()
            msg = 'seconds since last close: %s' % secs
            if imwin_ads.should_clear_cookies():
                msg += ' (will clear cookies on next imwin open)'
            dc.DrawText(msg, x, y)
            y += 20
예제 #11
0
    def OnMenuOpen(self, event: wx.MenuEvent) -> None:
        if event.GetMenu() is not self:
            # We may be just opening one of the submenus but we only
            # want to do this when opening the main menu.
            event.Skip()
            return

        main_window = wx.GetApp().GetTopWindow()
        all_windows = {
            w
            for w in wx.GetTopLevelWindows() if w is not main_window
        }

        for window in all_windows.difference(self._id_to_window.values()):
            if not window.Title:
                # We have bogus top-level windows because of the use
                # of AuiManager on the logging window (see issue #617)
                # so skip windows without a title.
                continue
            sub_menu = wx.Menu()
            for label, method in [
                ('Show/Hide', self.OnShowOrHide),
                ('Raise to top', self.OnRaiseToTop),
                ('Move to mouse', self.OnMoveToMouse),
            ]:
                menu_item = sub_menu.Append(wx.ID_ANY, label)
                sub_menu.Bind(wx.EVT_MENU, method, menu_item)
                self._id_to_window[menu_item.Id] = window

            # Place this submenu after the "Reset window positions"
            # but before the log viewer and debug window.
            position = len(self._id_to_window) / 3
            self.Insert(position, wx.ID_ANY, window.Title, sub_menu)
예제 #12
0
 def update_progress(self, message, elapsed_time, remaining_time=None):
     #
     # Disable everything if in a modal state. The progress bar
     # seems to eat memory in huge chunks if allowed to draw its
     # oh so shiny self while modal in the ultra awesome Mac
     # interface. But you have to admit, the design is disgustingly
     # elegant even if it does cause my ugly application to
     # crash horribly.
     #
     # Taken from Cody Precord's post
     # https://groups.google.com/forum/#!topic/wxpython-users/s8AQ64ptyCg
     #
     for win in wx.GetTopLevelWindows():
         if isinstance(win, wx.Dialog):
             if win.IsModal():
                 self.__progress_bar.Show(False)
                 return
     self.__progress_bar.Show(True)
     self.__progress_msg_ctrl.SetLabel(message)
     if remaining_time is not None:
         self.__progress_bar.SetValue(
             (100 * elapsed_time) /
             (elapsed_time + remaining_time + 0.00001))
         timestr = "Time %s/%s" % (
             secs_to_timestr(elapsed_time),
             secs_to_timestr(elapsed_time + remaining_time),
         )
     else:
         self.__progress_bar.Pulse()
         timestr = "Elapsed time: %s" % secs_to_timestr(elapsed_time)
     self.__timer.SetLabel(timestr)
     self.__progress_panel.Layout()
예제 #13
0
    def quit(self, force=True):
        self._logger.info("mainframe: in quit")
        if self.wxapp is not None:
            self._logger.info("mainframe: using self.wxapp")
            app = self.wxapp
        else:
            self._logger.info("mainframe: got app from wx")
            app = wx.GetApp()

        self._logger.info("mainframe: looping through toplevelwindows")
        for item in wx.GetTopLevelWindows():
            if item != self:
                if isinstance(item, wx.Dialog):
                    self._logger.info("mainframe: destroying %s", item)
                    if item.IsModal():
                        item.EndModal(wx.ID_CANCEL)
                    else:
                        item.Hide()
                else:
                    item.Hide()
        self._logger.info("mainframe: destroying %s", self)
        self.Hide()

        if app:

            def doexit():
                app.ExitMainLoop()
                wx.WakeUpMainThread()

            wx.CallLater(1000, doexit)
            if force:
                wx.CallLater(2500, app.Exit)
예제 #14
0
    def __init__(self, dialogname, onok=None):
        pcbnew_frame = \
            list(filter(lambda w: w.GetTitle().startswith('Pcbnew'), wx.GetTopLevelWindows()))[0]

        wx.Dialog.__init__(self, pcbnew_frame,
                           id=wx.ID_ANY,
                           title=dialogname,
                           pos=wx.DefaultPosition)

        self.ok_cbs = []
        if onok:
            self.ok_cbs.append(onok)

        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.main_sizer)


        # add ok and cancel buttons.
        sizer_ok_cancel = wx.BoxSizer(wx.HORIZONTAL)
        self.main_sizer.Add(sizer=sizer_ok_cancel, proportion=0, flag=wx.EXPAND)

        ok_button = wx.Button(self, wx.ID_OK, u"OK", wx.DefaultPosition, wx.DefaultSize, 0)
        ok_button.SetDefault()
        sizer_ok_cancel.Add(ok_button)#, proportion=1) #, flag=wx.ALL, border=5)
        ok_button.Bind(wx.EVT_BUTTON, self.OnOK)

        cancel_button = wx.Button(self, wx.ID_CANCEL, u"Cancel", wx.DefaultPosition, wx.DefaultSize, 0)
        sizer_ok_cancel.Add(cancel_button, 1) #, wx.ALL, 5)


        self.ok_cancel_sizer_index = 0
        #self.Layout()
        self.Centre(wx.BOTH)
예제 #15
0
    def openData(self):
        """A context manager to avoid holding files open.

        Mrc.bindFile uses numpy mem-mapping. The only way to
        close a mem-mapped file is to delete all references to
        the memmap object, which will then be cleaned up by
        the garbage collector.
        """
        try:
            # Test if this is a reentrant call.
            isOutermostCall = self._data is None
            if isOutermostCall:
                src = self._dataSource
                self._data = Mrc(src, 'r').data_withMrc(src)
            yield
        except IOError:
            dlg = wx.MessageDialog(
                wx.GetTopLevelWindows()[0],
                "Could not open data file: it may have been moved or deleted.",
                caption="IO Error",
                style=wx.OK)
            dlg.ShowModal()
            yield
        finally:
            if isOutermostCall:
                self._data = None
                gc.collect()
예제 #16
0
    def Run(self):
        "run pugin"
        pcb = pcbnew.GetBoard()

        self.pcb_assembly_path = os.path.dirname(
            pcb.GetFileName()) + PCB_ASSEMBLY_PACK_DIR
        if not os.path.exists(self.pcb_assembly_path):
            os.makedirs(self.pcb_assembly_path)

        # find pcbnew frame
        _pcbnew_frame = [
            x for x in wx.GetTopLevelWindows()
            if x.GetTitle().lower().startswith('pcbnew')
        ][0]
        # show dialog
        main_dialog = PCBAssemblyDialog(_pcbnew_frame)
        main_res = main_dialog.ShowModal()

        if main_dialog.chkbox_top.GetValue():
            top_en = True
        else:
            top_en = False

        if main_dialog.chkbox_bottom.GetValue():
            bottom_en = True
        else:
            bottom_en = False

        main_dialog.Destroy()

        self.plot_assembly_drawings(pcb, top_en, bottom_en)

        self.generate_xy_pos(pcb, top_en, bottom_en)
예제 #17
0
def installDefPackages(ver: VersionInfo = None, folder: str = None):
    dialog = wx.ProgressDialog(parent=wx.GetTopLevelWindows()[0],
                               title='Installing BEE2..',
                               message='Downloading default packages..',
                               maximum=100)
    # install default package pack
    # get the url
    link = get(beePackagesApiUrl).json()['assets'][0]['browser_download_url']
    # get the zip as bytes
    logger.info('downloading default package pack...')
    request = get(link, stream=True)
    # working variables
    zipdata = io.BytesIO()
    dialog.Update(0)

    dl = 0
    total_length = int(request.headers.get('content-length'))
    # download!
    for data in request.iter_content(chunk_size=1024):
        dl += len(data)
        zipdata.write(data)
        done = int(100 * dl / total_length)
        print(f'total: {total_length}, dl: {dl}, done: {done}')
        dialog.Update(done)

    logger.info('extracting...')
    dialog.Pulse('Extracting..')
    # convert to a byte stream, then zipfile object and then extract
    ZipFile(zipdata).extractall(
        config.load('beePath') if folder is None else folder)
    dialog.Close()
    logger.info('finished extracting!')
예제 #18
0
    def OnButton(self, evt):
        """Handles button events
        @param evt: event that called this handler
        @postcondition: Dialog is closed
        @postcondition: If Report Event then email program is opened

        """
        e_id = evt.GetId()
        if e_id == wx.ID_CLOSE:
            self.Close()
        elif e_id == ID_SEND:
            status, error = send_email_via_webbrowser(
                "%s Error Report" % self.task.about_title, self.err_msg,
                self.task.error_email_to)
            if status:
                self.Close()
            else:
                self._panel.text.AppendText(error)
                btn = wx.FindWindowById(ID_SEND, self)
                btn.Enable(False)
        elif e_id == wx.ID_ABORT:
            ErrorDialog.ABORT = True
            # Try a nice shutdown first time through
            app = wx.GetApp()
            for tlw in wx.GetTopLevelWindows():
                tlw.Destroy()

            wx.CallLater(500, app.ExitMainLoop)
            self.Close()
        elif e_id == wx.ID_IGNORE:
            self.user_requested_ignore[self._message] = True
            self.Close()
        else:
            evt.Skip()
예제 #19
0
    def Run(self):
        #self.pcb = GetBoard()
        import sys, os
        #mm_ius = 1000000.0
        _pcbnew_frame = [
            x for x in wx.GetTopLevelWindows()
            if x.GetTitle().lower().startswith('pcbnew')
        ][0]
        #aParameters = RoundTrackDlg(None)
        aParameters = Snap2Grid_Dlg(_pcbnew_frame)
        gridIndex = aParameters.m_comboBoxGrid.FindString(
            '0.1mm     (3.94mils)')
        aParameters.m_comboBoxGrid.SetSelection(gridIndex)
        #aParameters.m_comboBoxGrid.Append('0.1mm (3.94mils)')
        aParameters.m_radioBtnGO.SetValue(True)
        aParameters.Show()

        modal_result = aParameters.ShowModal()
        if modal_result == wx.ID_OK:
            grid = aParameters.m_comboBoxGrid.GetStringSelection()
            gridSizeMM = float(grid.split('mm')[0])
            if aParameters.m_radioBtnGO.GetValue():
                use_grid = 'gridorigin'
            elif aParameters.m_radioBtnAO.GetValue():
                use_grid = 'auxorigin'
            else:
                use_grid = 'topleft'
            snap2grid(gridSizeMM, use_grid)
        else:
            None  # Cancel
예제 #20
0
파일: WireIt.py 프로젝트: xesscorp/WireIt
 def findPcbnewWindow():
     """Find the window for the PCBNEW application."""
     windows = wx.GetTopLevelWindows()
     pcbnew = [w for w in windows if "PCB Editor" in w.GetTitle() or "Pcbnew" in w.GetTitle()]
     if len(pcbnew) != 1:
         raise Exception("Cannot find PCB Editor or Pcbnew window from title matching!")
     return pcbnew[0]
예제 #21
0
def get_shell_history():
    """
    This only works with some shells.
    """
    # try for ipython
    if 'get_ipython' in globals():
        a = list(get_ipython().history_manager.input_hist_raw)
        a.reverse()
        return a

    elif 'SPYDER_SHELL_ID' in _os.environ:
        try:
            p = _os.path.join(_settings.path_user, ".spyder2", "history.py")
            a = read_lines(p)
            a.reverse()
            return a
        except:
            pass

    # otherwise try pyshell or pycrust (requires wx)
    else:
        try:
            import wx
            for x in wx.GetTopLevelWindows():
                if type(x) in [wx.py.shell.ShellFrame, wx.py.crust.CrustFrame]:
                    a = x.shell.GetText().split(">>>")
                    a.reverse()
                    return a
        except:
            pass

    return ['shell history not available']
예제 #22
0
 def __init__(self, title='', parent=None, size=None, style=None):
     parent = parent or wx.GetTopLevelWindows()[0]
     size = size or (-1, -1)
     # wx.THICK_FRAME allows resizing
     style = style or wx.DEFAULT_DIALOG_STYLE | wx.THICK_FRAME
     wx.Dialog.__init__(self, parent, title=title, size=size, style=style)
     self.CenterOnParent()
예제 #23
0
 def _HideOtherWindows( self ):
     
     for tlw in wx.GetTopLevelWindows():
         
         if tlw == self:
             
             continue
             
         
         if not isinstance( tlw, ( ClientGUITopLevelWindows.Frame, ClientGUITopLevelWindows.NewDialog ) ):
             
             continue
             
         
         import ClientGUI
         
         if isinstance( tlw, ClientGUI.FrameGUI ):
             
             continue
             
         
         if not tlw.IsShown() or tlw.IsIconized():
             
             continue
             
         
         tlw.Hide()
         
         self._windows_hidden.append( tlw )
예제 #24
0
	def __init__(self):
		super().__init__(
			wx.GetTopLevelWindows()[0],  # parent
			title=f'Logs - {str(config.version)}',  # window title
			# those styles make so that the window can't minimize, maximize, resize and show on the taskbar
			style=wx.FRAME_NO_TASKBAR | wxStyles.TITLEBAR_ONLY_BUTTON_CLOSE ^ wx.RESIZE_BORDER
		)  # init the window
		logWindow.instance = self
		self.SetIcon( utilities.icon )
		self.SetSize(0, 0, 500, 365)
		sizer = wx.FlexGridSizer( rows=2, cols=1, gap=wx.Size(0, 0) )
		try:
			pos = config.load('logWindowPos')
			if pos is not None:
				self.SetPosition( wx.Point( pos ) )
			else:
				self.SetPosition( wx.Point( 100, 100 ) )
		except config.ConfigError as e:
			logger.warning(e)  # not a problem if it fails
		self.text = wx.TextCtrl(
			self,
			style=wx.TE_MULTILINE | wx.TE_READONLY | wx.VSCROLL | wx.TE_RICH,
			size=wx.Size( self.GetSize()[0], 300 )
		)  # make the textbox
		self.logHandler = logHandler()
		# set the log message format
		self.logHandler.setFormatter(
			logging.Formatter(
				# One letter for level name
				'[{levelname[0]}] {module}.{funcName}(): {message}\n',
				style='{',
			)
		)
		self.logHandler.setLevel(getLevel())
		logging.getLogger().addHandler(self.logHandler)
		# create bottom bar
		self.bottomBar = wx.Panel( self, size=wx.Size( self.GetSize()[0], 30) )  # makes the bottom "menu" bar
		self.clearBtn = wx.Button(  # makes the clear button
			self.bottomBar,
			label='Clear',
			size=wx.Size(52, 22),
			pos=wx.Point(10, 3)
		)
		self.levelChoice = wx.Choice(
			parent=self.bottomBar,
			size=wx.Size(80, 22),
			pos=wx.Point(self.GetSize()[0]-100, 3),
			choices=['Debug', 'Info', 'Warning', 'Error']
		)
		self.levelChoice.SetSelection( ( getLevel() / 10 ) - 1 )
		sizer.Add(self.text, border=wx.Bottom)
		sizer.Add(self.bottomBar)
		self.SetSizer(sizer)
		self.Bind( wx.EVT_CLOSE, self.OnClose, self )
		self.Bind( wx.EVT_MOVE_END, self.OnMoveEnd, self )
		self.Bind( wx.EVT_BUTTON, self.OnClearButtonPressed, self.clearBtn )
		self.Bind( wx.EVT_CHOICE, self.OnLevelChoice, self.levelChoice )
		dispatcher.send(Events.LogWindowCreated, window=self)
		updateVisibility()
		self.levelChoice.Refresh()
예제 #25
0
    def OnMenuOpen(self, event: wx.MenuEvent) -> None:
        if event.GetMenu() is not self:
            # We may be just opening one of the submenus but we only
            # want to do this when opening the main menu.
            event.Skip()
            return

        main_window = wx.GetApp().GetTopWindow()
        all_windows = {
            w
            for w in wx.GetTopLevelWindows() if w is not main_window
        }

        for window in all_windows.difference(self._id_to_window.values()):
            if not window.Title:
                # We have bogus top-level windows because of the use
                # of AuiManager on the logging window (see issue #617)
                # so skip windows without a title.
                continue
            menu_item = wx.MenuItem(self, wx.ID_ANY, window.Title)
            self.Bind(wx.EVT_MENU, self.OnWindowTitle, menu_item)
            self._id_to_window[menu_item.Id] = window

            # Place this menu item after the "Reset window positions"
            # but before the log viewer and debug window.
            position = len(self._id_to_window)
            self.Insert(position, menu_item)
예제 #26
0
파일: app.py 프로젝트: mw1602/Eelbrain
 def _get_active_frame(self):
     win = wx.Window.FindFocus()
     return wx.GetTopLevelParent(win)
     for w in wx.GetTopLevelWindows():
         if hasattr(w, 'IsActive') and w.IsActive():
             return w
     return wx.GetActiveWindow()
예제 #27
0
    def OnPaint(self, event):
        sz = self.GetClientSize()

        pdc = wx.BufferedPaintDC(self)
        try:
            dc = wx.GCDC(pdc)
        except Exception:
            dc = pdc

        isModalDialogShown = False
        for win in wx.GetTopLevelWindows():
            if isinstance(win, wx.Dialog) and win.IsModal():
                isModalDialogShown = True
                break

        dc.SetBrush(wx.BLACK_BRUSH)
        dc.DrawRectangle(0, 0, sz[0], sz[1])
        if not self.IsEnabled() and not isModalDialogShown:
            # a modal dialog set this window to disabled (not enabled), but
            # this windows is set to disabled if no selection can
            # be made (multiple selected images)
            # this rectangle should only be drawn if this windows is set to
            # disabled programmatically and not when a modal dialog is shown
            dc.SetBrush(
                wx.Brush(wx.Colour(90, 90, 90, 255), wx.HORIZONTAL_HATCH))
            dc.DrawRectangle(0, 0, sz[0], sz[1])
        elif self._imgProxy is not None:
            self.__DrawBitmap(dc)
            self.__DrawSection(dc)

        event.Skip()
예제 #28
0
    def on_close(self, evt=None):
        # Classifier needs to be told to close so it can clean up it's threads
        classifier = wx.FindWindowById(ID_CLASSIFIER) or wx.FindWindowByName(
            'Classifier')
        if classifier and classifier.Close() == False:
            return

        if any(wx.GetApp().get_plots()):
            dlg = wx.MessageDialog(
                self,
                'Some tools are open, are you sure you want to quit CPA?',
                'Quit CellProfiler Analyst?',
                wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
            response = dlg.ShowModal()
            if response != wx.ID_YES:
                return

        try:
            logging.debug("Shutting of Java VM")
            import javabridge
            if javabridge.get_env() is not None:
                javabridge.kill_vm()
        except:
            logging.debug("Failed to kill the Java VM")

        # Blow up EVVVVERYTHIIINGGG!!! Muahahahahhahahah!
        for win in wx.GetTopLevelWindows():
            logging.debug('Destroying: %s' % (win))
            win.Destroy()
        if self.tbicon is not None:
            self.tbicon.Destroy()

        self.Destroy()
예제 #29
0
 def Run(self):
     """
     """
     _pcbnew_frame = [
         x for x in wx.GetTopLevelWindows()
         if x.GetTitle().lower().startswith("pcbnew")
     ][0]
     wx_params = TraceClearance_Dlg(_pcbnew_frame)
     wx_params.m_clearance.SetValue("0.2")
     wx_params.m_bitmap.SetBitmap(
         wx.Bitmap(
             os.path.join(
                 os.path.dirname(os.path.realpath(__file__)),
                 "trace_clearance_dialog.png",
             )))
     modal_res = wx_params.ShowModal()
     clearance = pcbnew.FromMM(
         self.InputValid(wx_params.m_clearance.GetValue()))
     if clearance is not None:
         pcb = pcbnew.GetBoard()
         if modal_res == wx.ID_OK:
             tracks = selected_tracks(pcb)
             if len(tracks) > 0:
                 set_keepouts(pcb, tracks, clearance)
             else:
                 self.Warn("At least one track must be selected.")
         elif modal_res == wx.ID_CANCEL:
             wx_params.Destroy()
예제 #30
0
def app_windows_image():
    '''
    Returns a bitmap showing all the top level windows in this application.

    Other areas of the screen are blanked out.
    '''

    # get the union of all screen rectangles (this will be a big rectangle
    # covering the area of all monitors)
    rect = reduce(wx.Rect.Union, (m.Geometry for m in Monitor.All()))
    if "wxMSW" in wx.PlatformInfo:
        screen = getScreenBitmap(rect).PIL
    else:
        screen = wx.ScreenDC().GetAsBitmap().PIL

    mask = Image.new('RGBA', rect.Size, (255, 255, 255, 255))
    drawrect = lambda r: ImageDraw.Draw(mask).rectangle(
        [r.x, r.y, r.Right, r.Bottom], fill=(0, 0, 0, 0))

    # draw rectangles into a mask for each top level window (and the system tray)
    for r in [GetTrayRect()
              ] + [w.Rect for w in wx.GetTopLevelWindows() if w.IsShown()]:
        r.Offset((-rect.Position[0], -rect.Position[1]
                  ))  # some monitors may be in negative coordinate space...
        drawrect(r)

    # paste the mask into the screenshot--whiteing out areas not in our windows
    screen_full = screen.copy()
    screen.paste(mask, (0, 0), mask)

    return screen_full, screen