Exemplo n.º 1
0
 def OnCmdFileLocate(self, cmd, id):
     line = self.GetLine().strip()
     import pywin.framework.scriptutils
     m = patImport.match(line)
     if m:
         # Module name on this line - locate that!
         modName = m.group('name')
         fileName = pywin.framework.scriptutils.LocatePythonFile(modName)
         if fileName is None:
             win32ui.SetStatusText("Can't locate module %s" % modName)
             return 1  # Let the default get it.
         else:
             win32ui.GetApp().OpenDocumentFile(fileName)
     else:
         # Just to a "normal" locate - let the default handler get it.
         return 1
     return 0
Exemplo n.º 2
0
	def Colorize(self, start=0, end=-1):
		scintilla = self.scintilla
		stringVal = scintilla.GetTextRange(start, end)
		if start > 0:
			stylenum = scintilla.SCIGetStyleAt(start - 1)
			styleStart = self.GetStyleByNum(stylenum).name
		else:
			styleStart = None
#		trace("Coloring", start, end, end-start, len(stringVal), styleStart, self.scintilla.SCIGetCharAt(start))
		scintilla.SCIStartStyling(start, 31)
		self.style_buffer = array.array("c", chr(0)*len(stringVal))
		self.ColorizeString(stringVal, styleStart)
		scintilla.SCISetStylingEx(self.style_buffer)
		self.style_buffer = None
#		trace("After styling, end styled is", self.scintilla.SCIGetEndStyled())
		if self.bCompleteWhileIdle and not self.bHaveIdleHandler and end!=-1 and end < scintilla.GetTextLength():
			self.bHaveIdleHandler = 1
			win32ui.GetApp().AddIdleHandler(self.DoMoreColoring)
Exemplo n.º 3
0
 def __init__(self, title=None, defSize=None, queueing=flags.WQ_LINE,
              bAutoRestore=1, style=None,
              makeDoc=None, makeFrame=None, makeView=None):
     """ init the output window -
     Params
     title=None -- What is the title of the window
     defSize=None -- What is the default size for the window - if this
                     is a string, the size will be loaded from the ini file.
     queueing = flags.WQ_LINE -- When should output be written
     bAutoRestore=1 -- Should a minimized window be restored.
     style -- Style for Window, or None for default.
     makeDoc, makeFrame, makeView -- Classes for frame, view and window respectively.
     """
     if makeDoc is None:
         makeDoc = WindowOutputDocument
     if makeFrame is None:
         makeFrame = WindowOutputFrame
     if makeView is None:
         makeView = WindowOutputViewScintilla
     docview.DocTemplate.__init__(self, win32ui.IDR_PYTHONTYPE,
                                  makeDoc, makeFrame, makeView)
     self.SetDocStrings("\nOutput\n\nText Documents (*.txt)\n.txt\n\n\n")
     win32ui.GetApp().AddDocTemplate(self)
     self.writeQueueing = queueing
     self.errorCantRecreate = 0
     self.killBuffer = []
     self.style = style
     self.bAutoRestore = bAutoRestore
     self.title = title
     self.bCreating = 0
     self.interruptCount = 0
     # is a string - maintain size pos from ini file.
     if isinstance(defSize, type('')):
         self.iniSizeSection = defSize
         self.defSize = app.LoadWindowSize(defSize)
         self.loadedSize = self.defSize
     else:
         self.iniSizeSection = None
         self.defSize = defSize
     self.currentView = None
     self.outputQueue = queue.Queue(-1)
     self.mainThreadId = win32api.GetCurrentThreadId()
     self.idleHandlerSet = 0
     self.SetIdleHandler()
Exemplo n.º 4
0
 def SearchFile(self, handler, count):
     self.fndx = self.fndx + 1
     if self.fndx < len(self.flist):
         f = self.flist[self.fndx]
         if self.verbose:
             self.GetFirstView().Append('# ..' + f + '\n')
         # Directories may match the file type pattern, and files may be removed
         #  while grep is running
         if os.path.isfile(f):
             win32ui.SetStatusText("Searching " + f, 0)
             lines = open(f, 'r').readlines()
             for i in range(len(lines)):
                 line = lines[i]
                 if self.pat.search(line) is not None:
                     self.GetFirstView().Append(f + '(' + repr(i + 1) + ') ' + line)
     else:
         self.fndx = -1
         self.fpndx = self.fpndx + 1
         if self.fpndx < len(self.fplist):
             self.flist = glob.glob(
                 self.dp[
                     self.dpndx] +
                 '\\' +
                 self.fplist[
                     self.fpndx])
         else:
             self.fpndx = 0
             self.dpndx = self.dpndx + 1
             if self.dpndx < len(self.dp):
                 self.flist = glob.glob(
                     self.dp[
                         self.dpndx] +
                     '\\' +
                     self.fplist[
                         self.fpndx])
             else:
                 win32ui.SetStatusText("Search complete.", 0)
                 self.SetModifiedFlag(0)  # default to not modified.
                 try:
                     win32ui.GetApp().DeleteIdleHandler(self.SearchFile)
                 except:
                     pass
                 return 0
     return 1
Exemplo n.º 5
0
def _CheckNeedGUI():
    global isInprocApp
    if isInprocApp == -1:
        import win32ui
        isInprocApp = win32ui.GetApp().IsInproc()
    if isInprocApp:
        # MAY Need it - may already have one
        need = "pywin.debugger.dbgpyapp" not in sys.modules
    else:
        need = 0
    if need:
        import pywin.framework.app
        from . import dbgpyapp
        pywin.framework.app.CreateDefaultGUI(dbgpyapp.DebuggerPythonApp)

    else:
        # Check we have the appropriate editor
        # No longer necessary!
        pass
    return need
Exemplo n.º 6
0
    def DoMoreColoring(self, handler, count):
        try:
            scintilla = self.scintilla
            endStyled = scintilla.SCIGetEndStyled()
            lineStartStyled = scintilla.LineFromChar(endStyled)
            start = scintilla.LineIndex(lineStartStyled)
            end = scintilla.LineIndex(lineStartStyled + 1)
            textlen = scintilla.GetTextLength()
            if end < 0: end = textlen

            finished = end >= textlen
            self.Colorize(start, end)
        except (win32ui.error, AttributeError):
            # Window may have closed before we finished - no big deal!
            finished = 1

        if finished:
            self.bHaveIdleHandler = 0
            win32ui.GetApp().DeleteIdleHandler(handler)
        return not finished
Exemplo n.º 7
0
    def OnFileLocate(self, id, code):
        from . import scriptutils
        global lastLocateFileName  # save the new version away for next time...

        name = dialog.GetSimpleInput('File name', lastLocateFileName,
                                     'Locate Python File')
        if name is None:  # Cancelled.
            return
        lastLocateFileName = name
        # if ".py" supplied, rip it off!
        # should also check for .pys and .pyw
        if lastLocateFileName[-3:].lower() == '.py':
            lastLocateFileName = lastLocateFileName[:-3]
        lastLocateFileName = lastLocateFileName.replace(".", "\\")
        newName = scriptutils.LocatePythonFile(lastLocateFileName)
        if newName is None:
            win32ui.MessageBox("The file '%s' can not be located" %
                               lastLocateFileName)
        else:
            win32ui.GetApp().OpenDocumentFile(newName)
Exemplo n.º 8
0
    def __init__(self, doc, bgcolor=None):
        self.__showing = 0
        self.__setting = 0
        # base init
        GenView.__init__(self, bgcolor)

        # important: a rich edit ctrl have to be created the right template and the right document
        # (see MFC doc: RichEditCtrl and architecture MDI).
        # If you don't do this, the application crash on some operations (drag and drop, ...)
        sourceTemplate = SourceViewTemplate()
        win32ui.GetApp().AddDocTemplate(sourceTemplate)
        doc = SourceViewDocument(sourceTemplate)

        docview.RichEditView.__init__(self, doc)

        # view decor
        self._dlgBar = win32ui.CreateDialogBar()
        self.__ok = components.Button(self._dlgBar,grinsRC.IDC_BUTTON1)
        self.__apply = components.Button(self._dlgBar,grinsRC.IDC_BUTTON2)
        self.__revert = components.Button(self._dlgBar,grinsRC.IDC_BUTTON3)
        self.__autoWrapCtrl = components.CheckButton(self._dlgBar,grinsRC.IDC_AUTOWRAP)

        self.__text=''
        self.__colors = []
        self.__mother = None
        self.__readonly = 0
        self.__hasdlgbar = 0
        self.__closecallback = None
        self.__map0 = []
        self.__map1 = []
        self.__listener = None
        self.__lineToSelect = None

        # keep the current caret pos.
        # note: the GetCaretPos have to be called only when this view has the focus
        # otherwise, it returns the caret pos of another view (see win32 api doc).
        # it's why we don't call this method just before to use it (the view may not have the focus)
        self.__caretPos = (0, 0)

        self.__lastItemFound = None
        self._popup = None
Exemplo n.º 9
0
    def mainloop(self):
        if len(self._subwindows) == 1:
            self.show()
        self._os_timer_wnd = self.genericwnd()
        self._os_timer_wnd.create()
        self._os_timer_wnd.HookMessage(self.OnTimer, win32con.WM_TIMER)

        # com automation support
        self.enableCOMAutomation()

        # if timers already set before mainloop is called...
        if self._timers:
            self.StartTimer()

        # enter application loop
        win32ui.GetApp().RunLoop()

        # cleanup
        self.StopTimer()
        self._os_timer_wnd.DestroyWindow()
        self._os_timer_wnd = None
Exemplo n.º 10
0
	def Colorize(self, start=0, end=-1):
		scintilla = self.scintilla
		# scintilla's formatting is all done in terms of utf, so
		# we work with utf8 bytes instead of unicode.  This magically
		# works as any extended chars found in the utf8 don't change
		# the semantics.
		stringVal = scintilla.GetTextRange(start, end, decode=False)
		if start > 0:
			stylenum = scintilla.SCIGetStyleAt(start - 1)
			styleStart = self.GetStyleByNum(stylenum).name
		else:
			styleStart = None
#		trace("Coloring", start, end, end-start, len(stringVal), styleStart, self.scintilla.SCIGetCharAt(start))
		scintilla.SCIStartStyling(start, 31)
		self.style_buffer = array.array("b", (0,)*len(stringVal))
		self.ColorizeString(stringVal, styleStart)
		scintilla.SCISetStylingEx(self.style_buffer)
		self.style_buffer = None
#		trace("After styling, end styled is", self.scintilla.SCIGetEndStyled())
		if self.bCompleteWhileIdle and not self.bHaveIdleHandler and end!=-1 and end < scintilla.GetTextLength():
			self.bHaveIdleHandler = 1
			win32ui.GetApp().AddIdleHandler(self.DoMoreColoring)
Exemplo n.º 11
0
	def doSearch(self):
		self.dp = dirpath(self.dirpattern, self.recurse)
		self.SetTitle("Grep for %s in %s" % (self.greppattern, self.filpattern))
		#self.text = []
		self.GetFirstView().Append('#Search '+self.dirpattern+'\n')
		if self.verbose:
			self.GetFirstView().Append('#   ='+repr(self.dp.dirs)+'\n')
		self.GetFirstView().Append('# Files '+self.filpattern+'\n')
		self.GetFirstView().Append('#   For '+self.greppattern+'\n')
		self.fplist = self.filpattern.split(';')
		if self.casesensitive:
			self.pat = re.compile(self.greppattern)
		else:
			self.pat = re.compile(self.greppattern, re.IGNORECASE)
		win32ui.SetStatusText("Searching.  Please wait...", 0)
		self.dpndx = self.fpndx = 0
		self.fndx = -1
		if not self.dp:
			self.GetFirstView().Append("# ERROR: '%s' does not resolve to any search locations" % self.dirpattern)
			self.SetModifiedFlag(0)
		else:
			self.flist = glob.glob(self.dp[0]+'\\'+self.fplist[0])
			win32ui.GetApp().AddIdleHandler(self.SearchFile)
Exemplo n.º 12
0
def win_get_std_cursor(id):
    app = ui.GetApp()
    win_app = getattr(app, '_win_app', app)
    hcursor = win_app.LoadStandardCursor(id)
    return Cursor._from_win_cursor(hcursor)
Exemplo n.º 13
0
	def __init__(self):
		docview.RichEditDocTemplate.__init__(self, win32ui.IDR_TEXTTYPE, GrepDocument, GrepFrame, GrepView)
		self.SetDocStrings("\nGrep\nGrep\nGrep params (*.grep)\n.grep\n\n\n")
		win32ui.GetApp().AddDocTemplate(self)
		self.docparams = None
Exemplo n.º 14
0
    def ProcessArgs(self, args, dde=None):
        # If we are going to talk to a remote app via DDE, then
        # activate it!
        if len(args) < 1 or not args[
                0]:  # argv[0]=='' when started without args, just like Python.exe!
            return

        i = 0
        while i < len(args):
            argType = args[i]
            i += 1
            if argType.startswith('-'):
                # Support dash options. Slash options are misinterpreted by python init
                # as path and not finding usually 'C:\\' ends up in sys.path[0]
                argType = '/' + argType[1:]
            if not argType.startswith('/'):
                argType = win32ui.GetProfileVal("Python", "Default Arg Type",
                                                "/edit").lower()
                i -= 1  #  arg is /edit's parameter
            par = i < len(args) and args[i] or 'MISSING'
            if argType in ['/nodde', '/new', '-nodde', '-new']:
                # Already handled
                pass
            elif argType.startswith('/goto:'):
                gotoline = int(argType[len('/goto:'):])
                if dde:
                    dde.Exec("from pywin.framework import scriptutils\n"
                             "ed = scriptutils.GetActiveEditControl()\n"
                             "if ed: ed.SetSel(ed.LineIndex(%s - 1))" %
                             gotoline)
                else:
                    from . import scriptutils
                    ed = scriptutils.GetActiveEditControl()
                    if ed: ed.SetSel(ed.LineIndex(gotoline - 1))
            elif argType == "/edit":
                # Load up the default application.
                i += 1
                fname = win32api.GetFullPathName(par)
                if not os.path.isfile(fname):
                    # if we don't catch this, OpenDocumentFile() (actually
                    # PyCDocument.SetPathName() in
                    # pywin.scintilla.document.CScintillaDocument.OnOpenDocument)
                    # segfaults Pythonwin on recent PY3 builds (b228)
                    win32ui.MessageBox(
                        "No such file: %s\n\nCommand Line: %s" %
                        (fname, win32api.GetCommandLine()),
                        "Open file for edit", win32con.MB_ICONERROR)
                    continue
                if dde:
                    dde.Exec("win32ui.GetApp().OpenDocumentFile(%s)" %
                             (repr(fname)))
                else:
                    win32ui.GetApp().OpenDocumentFile(par)
            elif argType == "/rundlg":
                if dde:
                    dde.Exec(
                        "from pywin.framework import scriptutils;scriptutils.RunScript(%r, %r, 1)"
                        % (par, ' '.join(args[i + 1:])))
                else:
                    from . import scriptutils
                    scriptutils.RunScript(par, ' '.join(args[i + 1:]))
                return
            elif argType == "/run":
                if dde:
                    dde.Exec(
                        "from pywin.framework import scriptutils;scriptutils.RunScript(%r, %r, 0)"
                        % (par, ' '.join(args[i + 1:])))
                else:
                    from . import scriptutils
                    scriptutils.RunScript(par, ' '.join(args[i + 1:]), 0)
                return
            elif argType == "/app":
                raise RuntimeError(
                    "/app only supported for new instances of Pythonwin.exe")
            elif argType == '/dde':  # Send arbitary command
                if dde is not None:
                    dde.Exec(par)
                else:
                    win32ui.MessageBox(
                        "The /dde command can only be used\r\nwhen Pythonwin is already running"
                    )
                i += 1
            else:
                raise ValueError("Command line argument not recognised: %s" %
                                 argType)
Exemplo n.º 15
0
def _JumpToPosition(fileName, lineno, col = 1):
    view = win32ui.GetApp().OpenDocumentFile(fileName).GetFirstView()
    charNo = view.LineIndex(lineno-1)
    view.SetSel(charNo + col - 1)
Exemplo n.º 16
0
def DeleteIdleHandler(handler):
    print(
        "app.DeleteIdleHandler is deprecated - please use win32ui.GetApp().DeleteIdleHandler() instead."
    )
    return win32ui.GetApp().DeleteIdleHandler(handler)
Exemplo n.º 17
0
 def OnFileMRU(self, id, code):
     " Called when a File 1-n message is recieved "
     fileName = win32ui.GetRecentFileList()[id - win32ui.ID_FILE_MRU_FILE1]
     win32ui.GetApp().OpenDocumentFile(fileName)
Exemplo n.º 18
0
 def startPycheckerRun(self):
     self.result=None
     old=win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_APPSTARTING))
     win32ui.GetApp().AddIdleHandler(self.idleHandler)
     import thread
     thread.start_new(self.threadPycheckerRun,())
Exemplo n.º 19
0
 def __init__(self):
     docview.RichEditDocTemplate.__init__(self, win32ui.IDR_TEXTTYPE, TheDocument, TheFrame, TheView)
     self.SetDocStrings("\nPychecker\nPychecker\nPychecker params (*.pychecker)\n.pychecker\n\n\n")
     win32ui.GetApp().AddDocTemplate(self)
     self.docparams = None
Exemplo n.º 20
0
 def ProcessArgs(self, args, dde=None):
     # If we are going to talk to a remote app via DDE, then
     # activate it!
     if dde is not None: dde.Exec("self.Activate()")
     if len(args) and args[0] in ['/nodde', '/new']:
         del args[0]  # already handled.
     if len(args) < 1 or not args[
             0]:  # argv[0]=='' when started without args, just like Python.exe!
         return
     try:
         if args[0] and args[0][0] != '/':
             argStart = 0
             argType = win32ui.GetProfileVal("Python", "Default Arg Type",
                                             "/edit").lower()
         else:
             argStart = 1
             argType = args[0]
         if argStart >= len(args):
             raise TypeError("The command line requires an additional arg.")
         if argType == "/edit":
             # Load up the default application.
             if dde:
                 fname = win32api.GetFullPathName(args[argStart])
                 dde.Exec("win32ui.GetApp().OpenDocumentFile(%s)" %
                          (repr(fname)))
             else:
                 win32ui.GetApp().OpenDocumentFile(args[argStart])
         elif argType == "/rundlg":
             if dde:
                 dde.Exec(
                     "from pywin.framework import scriptutils;scriptutils.RunScript('%s', '%s', 1)"
                     % (args[argStart], ' '.join(args[argStart + 1:])))
             else:
                 from . import scriptutils
                 scriptutils.RunScript(args[argStart],
                                       ' '.join(args[argStart + 1:]))
         elif argType == "/run":
             if dde:
                 dde.Exec(
                     "from pywin.framework import scriptutils;scriptutils.RunScript('%s', '%s', 0)"
                     % (args[argStart], ' '.join(args[argStart + 1:])))
             else:
                 from . import scriptutils
                 scriptutils.RunScript(args[argStart],
                                       ' '.join(args[argStart + 1:]), 0)
         elif argType == "/app":
             raise RuntimeError(
                 "/app only supported for new instances of Pythonwin.exe")
         elif argType == '/dde':  # Send arbitary command
             if dde is not None:
                 dde.Exec(args[argStart])
             else:
                 win32ui.MessageBox(
                     "The /dde command can only be used\r\nwhen Pythonwin is already running"
                 )
         else:
             raise TypeError("Command line arguments not recognised")
     except:
         # too early for print anything.
         win32ui.DisplayTraceback(sys.exc_info(),
                                  " - error processing command line args")
Exemplo n.º 21
0
        eb = self.GetDlgItem(108)
        item = eb.GetLine(0)
        self.newitems.append(item)
        lb = self.GetDlgItem(107)
        i = lb.AddString(item)
        lb.SetSel(i, 1)
        return 1

    def OnListDoubleClick(self, cmd, code):
        if code == win32con.LBN_DBLCLK:
            self.OnOK()
            return 1

    def OnOK(self):
        lb = self.GetDlgItem(107)
        self.selections = lb.GetSelTextItems()
        self._obj_.OnOK()

    def getItems(self):
        return self.selections

    def getNew(self):
        return self.newitems

try:
    win32ui.GetApp().RemoveDocTemplate(greptemplate)
except NameError:
    pass

greptemplate = TheTemplate() 
Exemplo n.º 22
0
 def TakeDefaultAction(self):
     win32ui.GetApp().OpenDocumentFile(self.path)
Exemplo n.º 23
0
 def OnCloseDocument(self):
     try:
         win32ui.GetApp().DeleteIdleHandler(self.idleHandler)
     except:
         pass
     return self._obj_.OnCloseDocument()
Exemplo n.º 24
0
                                     BitmapDocument, BitmapFrame, BitmapView)

    def MatchDocType(self, fileName, fileType):
        doc = self.FindOpenDocument(fileName)
        if doc: return doc
        ext = os.path.splitext(fileName)[1].lower()
        if ext == '.bmp':  # removed due to PIL! or ext=='.ppm':
            return win32ui.CDocTemplate_Confidence_yesAttemptNative
        return win32ui.CDocTemplate_Confidence_maybeAttemptForeign


#		return win32ui.CDocTemplate_Confidence_noAttempt

# For debugging purposes, when this module may be reloaded many times.
try:
    win32ui.GetApp().RemoveDocTemplate(bitmapTemplate)
except NameError:
    pass

bitmapTemplate = BitmapTemplate()
bitmapTemplate.SetDocStrings(
    '\nBitmap\nBitmap\nBitmap (*.bmp)\n.bmp\nPythonBitmapFileType\nPython Bitmap File'
)
win32ui.GetApp().AddDocTemplate(bitmapTemplate)

# This works, but just didnt make it through the code reorg.
# class PPMBitmap(Bitmap):
#	def LoadBitmapFile(self, file ):
#		magic=file.readline()
#		if magic <> "P6\n":
#			raise TypeError, "The file is not a PPM format file"
Exemplo n.º 25
0
 def __init__(self):
     self.oldCallbackCaller = None
     WinApp.__init__(self, win32ui.GetApp())
     self.idleHandlers = []
Exemplo n.º 26
0
        is created.
        """
        self.strokes = []
        return 1


class ScribbleView(pywin.mfc.docview.ScrollView):
    def OnInitialUpdate(self):
        self.SetScrollSizes(win32con.MM_TEXT, (0, 0))


# Now we do the work to create the document template, and
# register it with the framework.

# For debugging purposes, we first attempt to remove the old template.
# This is not necessary once our app becomes stable!
try:
    win32ui.GetApp().RemoveDocTemplate(template)
except NameError:
    # havent run this before - thats ok
    pass

# Now create the template object itself...
template = ScribbleTemplate(None, ScribbleDocument, None, ScribbleView)
# Set the doc strings for the template.
docs = '\nPyScribble\nPython Scribble Document\nScribble documents (*.psd)\n.psd'
template.SetDocStrings(docs)

# Then register it with MFC.
win32ui.GetApp().AddDocTemplate(template)
Exemplo n.º 27
0
 def HandleOnFileNew(self, id, code):
     " Called when FileNew message is received "
     win32ui.GetApp().OnFileNew()
Exemplo n.º 28
0
 def SetIdleHandler(self):
     if not self.idleHandlerSet:
         debug("Idle handler set\n")
         win32ui.GetApp().AddIdleHandler(self.QueueIdleHandler)
         self.idleHandlerSet = 1
Exemplo n.º 29
0
				keyname = pywin.scintilla.view.configManager.get_key_binding( event, ["editor"] )
				if keyname is not None:
					text = text + "\t" + keyname
				submenu.AppendMenu(flags, id, text)

		mainMenu = self.GetSharedMenu()
		editMenu = mainMenu.GetSubMenu(1)
		editMenu.AppendMenu(win32con.MF_SEPARATOR, 0, "")
		editMenu.AppendMenu(win32con.MF_STRING | win32con.MF_POPUP | win32con.MF_ENABLED, submenu.GetHandle(), "&Source Code")

	def _CreateDocTemplate(self, resourceId):
		return win32ui.CreateDocTemplate(resourceId)

	def CreateWin32uiDocument(self):
		return self.DoCreateDoc()

	def GetPythonPropertyPages(self):
		"""Returns a list of property pages
		"""
		from pywin.scintilla import configui
		return EditorTemplateBase.GetPythonPropertyPages(self) + [configui.ScintillaFormatPropertyPage()]
		
# For debugging purposes, when this module may be reloaded many times.
try:
	win32ui.GetApp().RemoveDocTemplate(editorTemplate)
except NameError:
	pass

editorTemplate = SyntEditTemplate()
win32ui.GetApp().AddDocTemplate(editorTemplate)
Exemplo n.º 30
0
 def OnQueryDragIcon(self):
     return win32ui.GetApp().LoadIcon(self.iconId)