# Programmer: Franz Steinhaeusler
# E-mail: francescoa@users.sourceforge.net
# Note: You must reply to the verification e-mail to get through.
#
# Copyright 2004-2005 Franz Steinhaeusler
#
# Distributed under the terms of the GPL (GNU Public License)
#
# DrPython is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#Plugin
#KeyBoard Macros
# 0.0.0 26.09.2004
# 0.0.1 28.09.2004
# 0.0.2 02.10.2004
# 0.0.3 11.10.2004
#bugfix (forgot to Replace DrText with DrMacroText)
# 0.0.4 20.10.2004 (line endings unix)
# 0.0.5 26.10.2004 Adapted Changes from Open File
#take care: should be loaded rather at the beginning: at least befor sessions
# 0.0.6 20.12.2004 Adapted Changes from Open File as of drpython 3.7.8
# 0.0.7 07.01.2004 Adapted Changes from Open File as of drpython 3.8.3
# 0.0.8 21.01.2004 Adapted Changes from Open File as of drpython 3.9.1
# 0.0.9 24.01.2004 Adapted Changes from Open File as of drpython 3.9.3
# 0.1.0 15.02.2005 Adapted Changes from DrPython of drpython 3.10.4 (no need to overwrite onopen anymore)
# 0.1.1 08.04.2007
#for changes please see changelog.txt
#this is needed for PyChecker
import sys
#sys.path.append('c:/Eigene Dateien/python/drpython')
import wx
from drText import DrText
import drShortcuts
import os
from drpython import drPanel
from drPrompt import DrPrompt
from drFindReplaceDialog import drFindReplaceDialog, drFinder
import drFileDialog
import drPrefsFile
import drEncoding
def OnAbout(DrFrame):
NameAndVersion = "KeyBoard Macros:\n\nVersion: 0.1.1\n"
AboutString = NameAndVersion + "Franz Steinhaeusler\n\nReleased under the GPL.\n"
DrFrame.ShowMessage(AboutString, "About")
def OnHelp(DrFrame):
DrFrame.ShowMessage("KeyBoard Macros.\nNo Help available yet.", "Help")
def OnPreferences(DrFrame):
def GetIntFromBool (b):
if b:
return 1
else:
return 0
d = wx.Dialog(DrFrame, -1, ("KeyBoard Macro Preferences"), wx.DefaultPosition, wx.Size(192, 120), wx.DEFAULT_DIALOG_STYLE | wx.THICK_FRAME)
chkExtendedFunctions = wx.CheckBox(d, -1, "Extended Functions", wx.Point(20, 20))
wx.Button(d, wx.ID_CANCEL, "Cancel", wx.Point(10, 50))
wx.Button(d, wx.ID_OK, "Ok", wx.Point(90, 50))
chkExtendedFunctions.SetValue(DrFrame.KeyBoardMacros_ExtendedFunctions)
if d.ShowModal() == wx.ID_OK:
f = file(DrFrame.pluginspreferencesdirectory + "/keyboardmacros.preferences.dat", 'w')
DrFrame.KeyBoardMacros_ExtendedFunctions = chkExtendedFunctions.GetValue()
f.write("<keyboardmacros.extendedfunctions>" + str(GetIntFromBool (DrFrame.KeyBoardMacros_ExtendedFunctions)) + "</keyboardmacros.extendedfunctions>\n")
f.close()
d.Destroy()
class LoadMacroSelectiondlg(wx.Dialog):
def __init__ (self, parent, choices):
wx.Dialog.__init__ (self, parent, -1, "Choose Macro", wx.DefaultPosition, wx.Size(600, 300), wx.DEFAULT_DIALOG_STYLE | wx.MAXIMIZE_BOX | wx.THICK_FRAME | wx.RESIZE_BORDER)
self.btnOk = wx.Button(self, wx.ID_OK, "&Ok", pos = (490, 50))
self.btnCancel = wx.Button(self, wx.ID_CANCEL, "&Cancel", pos = (490, 100))
self.list = wx.ListBox(self, 403, pos = (20, 35), size = (450, 200), choices = choices)
self.Bind(wx.EVT_BUTTON, self.OnbtnOk, id = wx.ID_OK)
self.Bind(wx.EVT_BUTTON, self.OnbtnCancel, id = wx.ID_CANCEL)
self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnbtnOk)
self.list.SetSelection (0)
self.list.SetFocus ()
self.btnOk.SetDefault()
def OnbtnOk (self, event):
self.EndModal(1)
def OnbtnCancel (self, event):
self.EndModal(0)
#overwrite standard DrText behaviour
class DrMacroText(DrText):
def __init__(self, parent, id, grandparent):
DrText.__init__(self, parent, id, grandparent)
self.Bind(wx.EVT_CHAR, self.OnChar)
def OnKeyDown(self, event):
if self.grandparent.KeyBoardMacros_Recording:
self.EventAppend (event)
if event.GetKeyCode() == wx.stc.wx.WXK_NUMPAD_ENTER:
result = wx.stc.wx.WXK_NUMPAD_ENTER
self.CmdKeyExecute(wx.stc.STC_CMD_NEWLINE)
else:
result = self.grandparent.RunShortcuts(event, self, self.DisableShortcuts)
#print result, event.GetKeyCode()
# if event.GetKeyCode() < 256 and event.GetKeyCode() > 32:
#if not self.GetParent().GetParent().GetParent().GetParent().GetParent().GetActiveSTC().AutoCompActive():
# self.GetParent().GetParent().GetParent().GetParent().GetParent().OnFindAndComplete(None, event.GetKeyCode())
#print "started"
#return
#print chr(event.GetKeyCode()).isspace()
# return
if result > -1:
if (result == wx.stc.STC_CMD_NEWLINE or result == wx.stc.wx.WXK_NUMPAD_ENTER) and (self.grandparent.prefs.docautoindent):
self._autoindent()
if result == wx.stc.STC_CMD_TAB:
#Check Indentation for trailing spaces
pos = self.GetCurrentPos()
linenumber = self.LineFromPosition(pos)
lpos = pos - self.PositionFromLine(linenumber) - 1
ltext = self.GetLine(linenumber).rstrip(self.GetEndOfLineCharacter())
#only proceed if the text up to this point is whitespace.
if self.renonwhitespace.search(ltext[:lpos]) is not None:
return
#Get the position of where the full indentation ends:
lnws = len(ltext.rstrip())
fiendsat = lnws + (ltext[lnws:].count(self.addchar) * len(self.addchar))
#Get the diff betwixt this and the current pos:
difftwixt = len(ltext) - fiendsat
if difftwixt > 0:
#Check to make sure you are just looking at spaces:
target = ltext[fiendsat:]
for a in target:
if a != ' ':
return
#Remove the extra spaces
self.SetTargetStart(pos - difftwixt)
self.SetTargetEnd(pos)
self.ReplaceTarget('')
#/Check Indentation for trailing spaces
elif result == wx.stc.STC_CMD_DELETEBACK:
if not self.grandparent.prefs.docusetabs[self.filetype]:
pos = self.GetCurrentPos() - 1
if chr(self.GetCharAt(pos)) == ' ':
x = 0
l = self.grandparent.prefs.doctabwidth[self.filetype]
while x < l:
c = chr(self.GetCharAt(pos))
if c == ' ':
self.CmdKeyExecute(wx.stc.STC_CMD_DELETEBACK)
else:
x = l
x += 1
pos = pos - 1
else:
event.Skip()
else:
event.Skip()
#---Label---#000000#FFFFFF---------------------------------
def OnChar (self, event):
if self.grandparent.KeyBoardMacros_Recording:
self.EventAppend (event)
event.Skip()
def EventAppend (self, event):
self.grandparent.KeyBoardMacros_macro_events_collected.append([])
self.grandparent.KeyBoardMacros_macro_events_collected[-1].append (event.m_altDown)
self.grandparent.KeyBoardMacros_macro_events_collected[-1].append (event.m_controlDown)
self.grandparent.KeyBoardMacros_macro_events_collected[-1].append (event.m_keyCode)
self.grandparent.KeyBoardMacros_macro_events_collected[-1].append (event.m_metaDown)
self.grandparent.KeyBoardMacros_macro_events_collected[-1].append (event.m_rawCode)
self.grandparent.KeyBoardMacros_macro_events_collected[-1].append (event.m_rawFlags)
self.grandparent.KeyBoardMacros_macro_events_collected[-1].append (event.m_scanCode)
self.grandparent.KeyBoardMacros_macro_events_collected[-1].append (event.m_shiftDown)
self.grandparent.KeyBoardMacros_macro_events_collected[-1].append (event.m_x)
self.grandparent.KeyBoardMacros_macro_events_collected[-1].append (event.m_y)
self.grandparent.KeyBoardMacros_macro_events_collected[-1].append (event.GetEventType())
self.grandparent.KeyBoardMacros_macro_events_collected[-1].append (event.GetId())
def Plugin(DrFrame):
#=========================================================================
#overwrite Core Methods
def OnMacroNew(event):
#small trick :)(but not exemplary)
self = DrFrame
l = len(self.txtDocumentArray)
unumbers = map(lambda x: x.untitlednumber, self.txtDocumentArray)
unumbers.sort()
x = 0
last = 0
while x < l:
if unumbers[x] > 0:
if unumbers[x] != (last + 1):
x = l
else:
last = unumbers[x]
x = x + 1
else:
x = x + 1
last = last + 1
nextpage = drPanel(self.documentnotebook, self.ID_APP)
self.txtDocumentArray.append(DrMacroText(nextpage, self.ID_APP, self))
nextpage.SetSTC(self.txtDocumentArray[l])
self.documentnotebook.AddPage(nextpage, "Untitled " + str(last))
self.txtDocumentArray[l].untitlednumber = last
self.txtDocumentArray[l].Finder.Copy(self.txtDocument.Finder)
self.lastprogargsArray.append("")
self.txtDocumentArray[l].SetTargetPosition(l)
self.txtDocument.IsActive = False
self.txtDocument.OnModified(None)
self.setDocumentTo(l)
self.txtDocument.SetupPrefsDocument(1)
self.reloaddocumentsmenu()
self.txtDocument.SetSTCFocus(True)
self.PPost(self.EVT_DRPY_NEW)
def InitMacroPlugin():
#small trick :)(but not exemplary)
self = DrFrame
fn = DrFrame.txtDocument.filename
DrFrame.txtDocument.Destroy()
DrFrame.docPosition = 0
self.txtDocument = DrMacroText(self.currentpage, self.ID_DOCUMENT_BASE, self)
self.currentpage.SetSTC(self.txtDocument)
DrFrame.txtDocument.SetTargetPosition(0)
DrFrame.txtDocument.untitlednumber = 1
DrFrame.txtDocument.filename = fn
DrFrame.txtDocumentArray = [DrFrame.txtDocument]
DrFrame.STCKeycodeArray = drShortcuts.SetSTCShortcuts(DrFrame.txtDocument, DrFrame.STCShortcuts, DrFrame.ShortcutsUseDefault)
DrFrame.txtDocument.OnModified(None)
DrFrame.txtDocument.SetupPrefsDocument()
DrFrame.txtDocument.SetFocus()
DrFrame.txtDocument.OnPositionChanged(None)
if len(sys.argv) > 1:
f = sys.argv[1]
if self.PLATFORM_IS_WIN:
f = f.replace("\\", "/")
if not os.path.exists(f):
if self.Ask('"' + f + '" Does not exist. Create?', 'File Does Not Exist'):
try:
fobj = file(f, 'wb')
fobj.close()
except:
self.ShowMessage('Error Creating "' + f + '"')
if os.path.exists(f):
self.OpenFile(f, False)
self.txtDocument.OnModified(None)
x = 2
l = len(sys.argv)
while x < l:
f = sys.argv[x]
if self.PLATFORM_IS_WIN:
f = f.replace("\\", "/")
self.OpenFile(f, True)
self.txtDocument.OnModified(None)
x = x + 1
else:
try:
os.chdir(self.ddirectory)
except:
self.ShowMessage('Error Changing to Default Directory: "%s"' % (self.ddirectory), 'Preferences Error')
self.ddirectory = self.userpreferencesdirectory
os.chdir(self.ddirectory)
#toadd userpreferencesdirectory
#=========================================================================
#actual Plugin Functions
def OnMacroStartStopRecording (event):
DrFrame.KeyBoardMacros_Recording = not DrFrame.KeyBoardMacros_Recording
if DrFrame.KeyBoardMacros_Recording:
DrFrame.KeyBoardMacros_macro_events_collected = []
DrFrame.KeyBoardMacros_BlinkStatusBarTimer = wx.Timer(DrFrame)
DrFrame.KeyBoardMacros_BlinkStatusBarTimer.Start(500)
else:
#circumstantial
#if not removed, after the second replay, a recursion occurs
#the last parameter is stored; and starts a new macro start
DrFrame.KeyBoardMacros_BlinkStatusBarTimer.Stop()
DrFrame.SetStatusText("", 2)
if event.GetEventType() == wx.EVT_KEY_DOWN.evtType[0]:
DrFrame.KeyBoardMacros_macro_events_collected.pop()
DrFrame.KeyBoardMacros_CurrentMacroName = "Temporary Macro"
if DrFrame.KeyBoardMacros_macro_events_collected:
DrFrame.KeyBoardMacros_macro_recorded = True
def OnMacroReplay (event):
#is this variable needed?
if DrFrame.KeyBoardMacros_macro_events_collected == []:
DrFrame.ShowMessage("No Macro Recorded", "Macros")
return
for i in range (len(DrFrame.KeyBoardMacros_macro_events_collected)):
evt = wx.KeyEvent()
evt.m_altDown = DrFrame.KeyBoardMacros_macro_events_collected[i][0]
evt.m_controlDown = DrFrame.KeyBoardMacros_macro_events_collected[i][1]
evt.m_keyCode = DrFrame.KeyBoardMacros_macro_events_collected[i][2]
evt.m_metaDown = DrFrame.KeyBoardMacros_macro_events_collected[i][3]
evt.m_rawCode = DrFrame.KeyBoardMacros_macro_events_collected[i][4]
evt.m_rawFlags = DrFrame.KeyBoardMacros_macro_events_collected[i][5]
evt.m_scanCode = DrFrame.KeyBoardMacros_macro_events_collected[i][6]
evt.m_shiftDown = DrFrame.KeyBoardMacros_macro_events_collected[i][7]
evt.m_x = DrFrame.KeyBoardMacros_macro_events_collected[i][8]
evt.m_y = DrFrame.KeyBoardMacros_macro_events_collected[i][9]
evt.SetEventType(DrFrame.KeyBoardMacros_macro_events_collected[i][10])
evt.SetId(DrFrame.KeyBoardMacros_macro_events_collected[i][11])
DrFrame.txtDocument.GetEventHandler().ProcessEvent(evt)
def OnMacroLoad(event):
#temporary macro save?
if DrFrame.KeyBoardMacros_macro_recorded:
answer = wx.MessageBox('Would you like to save current Keystroke macro?', "Macros", wx.YES_NO | wx.ICON_QUESTION)
if answer == wx.YES:
OnMacroSave(event)
macronames = os.listdir (DrFrame.KeyBoardMacros_MacroDir)
#case insensitive
#split extension
macronames = [i[:-4] for i in macronames]
#todo: option or nocase compare?
macronames.sort (lambda a, b: cmp(a.lower(), b.lower()))
dlg = LoadMacroSelectiondlg (DrFrame, macronames)
if dlg.ShowModal() == 0:
dlg.Destroy()
return
if not dlg.list.GetSelections():
return
macroname = dlg.list.GetStringSelection()
DrFrame.KeyBoardMacros_CurrentMacroName = macroname
macroname = DrFrame.KeyBoardMacros_MacroDir + '/'+ macroname + '.dma'
dlg.Destroy()
f= open(macroname, "r")
DrFrame.KeyBoardMacros_macro_events_collected = []
for i in f.readlines():
DrFrame.KeyBoardMacros_macro_events_collected.append ([])
elements = i.split()
DrFrame.KeyBoardMacros_macro_events_collected[-1].append (eval(elements[0]))
DrFrame.KeyBoardMacros_macro_events_collected[-1].append (eval(elements[1]))
DrFrame.KeyBoardMacros_macro_events_collected[-1].append (int(elements[2]))
DrFrame.KeyBoardMacros_macro_events_collected[-1].append (eval(elements[3]))
DrFrame.KeyBoardMacros_macro_events_collected[-1].append (int(elements[4]))
DrFrame.KeyBoardMacros_macro_events_collected[-1].append (int(elements[5]))
DrFrame.KeyBoardMacros_macro_events_collected[-1].append (eval(elements[6]))
DrFrame.KeyBoardMacros_macro_events_collected[-1].append (eval(elements[7]))
DrFrame.KeyBoardMacros_macro_events_collected[-1].append (int(elements[8]))
DrFrame.KeyBoardMacros_macro_events_collected[-1].append (int(elements[9]))
DrFrame.KeyBoardMacros_macro_events_collected[-1].append (int(elements[10]))
DrFrame.KeyBoardMacros_macro_events_collected[-1].append (int(elements[11]))
f.close()
def OnMacroSave(event):
if DrFrame.KeyBoardMacros_macro_events_collected == []:
DrFrame.ShowMessage("No Macro recorded", "Warning")
return
elif not DrFrame.KeyBoardMacros_macro_recorded:
DrFrame.ShowMessage("No Macro to save", "Warning")
return
else:
if not os.path.exists(DrFrame.KeyBoardMacros_MacroDir):
os.mkdir(DrFrame.KeyBoardMacros_MacroDir)
olddir = DrFrame.ddirectory
DrFrame.ddirectory = DrFrame.KeyBoardMacros_MacroDir
dlg = drFileDialog.FileDialog(DrFrame, "Save File As", "DrPython Macro (*.dma)|*.dma", IsASaveDialog = True)
DrFrame.ddirectory = olddir
if dlg.ShowModal() == wx.ID_OK:
fname = dlg.GetPath().replace("\\", "/")
if fname.lower()[-4:] != '.dma':
fname += '.dma'
DrFrame.KeyBoardMacros_CurrentMacroName = os.path.splitext (os.path.basename(fname)) [0]
else:
return
DrFrame.KeyBoardMacros_macro_recorded = False
f = open (fname, "w")
for i in DrFrame.KeyBoardMacros_macro_events_collected:
for j in i:
f.write (str(j)+' ')
f.write ('\n')
f.close()
def OnDisplayMacroName(event):
if DrFrame.KeyBoardMacros_CurrentMacroName =='':
DrFrame.ShowMessage("No Macro", "Current Macro")
else:
DrFrame.ShowMessage(DrFrame.KeyBoardMacros_CurrentMacroName, "Current Macro")
def OnStatusBarMacroBlinkTimer (event):
DrFrame.KeyBoardMacros_toggle_status_bar = not DrFrame.KeyBoardMacros_toggle_status_bar
if DrFrame.KeyBoardMacros_toggle_status_bar:
DrFrame.SetStatusText("Recording Macro", 2)
else:
DrFrame.SetStatusText("", 2)
# Init of Macro Plugin
InitMacroPlugin ()
#DrFrame.OpenFile = OpenMacroFile
DrFrame.OnNew = OnMacroNew
#vars
DrFrame.Bind (wx.EVT_TIMER, OnStatusBarMacroBlinkTimer)
DrFrame.KeyBoardMacros_ExtendedFunctions = True
DrFrame.KeyBoardMacros_toggle_status_bar = False
DrFrame.KeyBoardMacros_macro_recorded = False
DrFrame.KeyBoardMacros_macro_events_collected = []
DrFrame.KeyBoardMacros_MacroDir = DrFrame.pluginsdatdirectory + "/macros"
DrFrame.KeyBoardMacros_Recording = False
DrFrame.KeyBoardMacros_CurrentMacroName = ""
if os.path.exists(DrFrame.pluginspreferencesdirectory + "/keyboardmacros.preferences.dat"):
f = file(DrFrame.pluginspreferencesdirectory + "/keyboardmacros.preferences.dat", 'r')
text = f.read()
f.close()
DrFrame.KeyBoardMacros_ExtendedFunctions = drPrefsFile.GetPrefFromText(DrFrame.KeyBoardMacros_ExtendedFunctions, text, "keyboardmacros.extendedfunctions", True)
ID_MACRO_START_STOP_RECORDING = DrFrame.GetNewId()
ID_MACRO_REPLAY = DrFrame.GetNewId()
DrFrame.Bind(wx.EVT_MENU, OnMacroStartStopRecording, id = ID_MACRO_START_STOP_RECORDING)
DrFrame.Bind(wx.EVT_MENU, OnMacroReplay, id=ID_MACRO_REPLAY)
DrFrame.AddPluginFunction("KeyBoardMacros", "Start/Stop Macro Recording", OnMacroStartStopRecording)
DrFrame.AddPluginFunction("KeyBoardMacros", "Macro Replay", OnMacroReplay)
if DrFrame.KeyBoardMacros_ExtendedFunctions:
ID_MACRO_LOAD = DrFrame.GetNewId()
ID_MACRO_SAVE = DrFrame.GetNewId()
ID_MACRO_DISPLAY_NAME = DrFrame.GetNewId()
DrFrame.Bind(wx.EVT_MENU, OnMacroLoad, id=ID_MACRO_LOAD)
DrFrame.Bind(wx.EVT_MENU, OnMacroSave, id=ID_MACRO_SAVE)
DrFrame.Bind(wx.EVT_MENU, OnDisplayMacroName, id=ID_MACRO_DISPLAY_NAME)
DrFrame.AddPluginFunction("KeyBoardMacros", "Load Macro", OnMacroLoad)
DrFrame.AddPluginFunction("KeyBoardMacros", "Save Macro", OnMacroSave)
DrFrame.AddPluginFunction("KeyBoardMacros", "Display Macro Name", OnDisplayMacroName)
DrFrame.LoadPluginShortcuts('KeyBoardMacros')
kbmacrosmenu = wx.Menu()
kbmacrosmenu.Append(ID_MACRO_START_STOP_RECORDING, DrFrame.GetPluginMenuLabel('KeyBoardMacros', 'Start/Stop Macro Recording', 'Start/Stop Macro Recording'))
kbmacrosmenu.Append(ID_MACRO_REPLAY, DrFrame.GetPluginMenuLabel('KeyBoardMacros', 'Macro Replay', 'Macro Replay'))
if DrFrame.KeyBoardMacros_ExtendedFunctions:
kbmacrosmenu.Append(ID_MACRO_LOAD, DrFrame.GetPluginMenuLabel('KeyBoardMacros', 'Load Macro', 'Load Macro...'))
kbmacrosmenu.Append(ID_MACRO_SAVE, DrFrame.GetPluginMenuLabel('KeyBoardMacros', 'Save Macro', 'Save Macro...'))
kbmacrosmenu.Append(ID_MACRO_DISPLAY_NAME, DrFrame.GetPluginMenuLabel('KeyBoardMacros', 'Display Macro Name', 'Display Macro Name'))
DrFrame.editmenu.AppendSeparator()
DrFrame.editmenu.AppendMenu(DrFrame.GetNewId(), "Keyboard macros", kbmacrosmenu)