Example #1
0
 def dlg_import_choose_mcrs(self):
     l, lt = '\n', '\n  '
     while True:
         imp_file = app.dlg_file(True, '', '',
                                 'Cuda macros|*.cuda-macros|All file|*.*')
         if imp_file is None:
             return (None, None)
         vers_mcrs = apx._json_loads(open(imp_file).read())
         if vers_mcrs is None:
             if app.ID_OK != app.msg_box(
                     'No macros in file\n  ' + imp_file +
                     '\n\nChoose another file?', app.MB_OKCANCEL):
                 return (None, None)
             continue  #while
         vers = vers_mcrs.get('vers', {})
         if (app.app_api_version() < vers.get('ver-api',
                                              app.app_api_version())
                 and app.ID_OK != app.msg_box(
                     'Macros from' + lt + imp_file + l +
                     'are recorded in CudaText with version' + lt + '"{}"' +
                     l + 'Your CudaText has older version' + lt + '"{}"' +
                     l + '' + l + 'No guarantee of correct working!' + l +
                     '' + l + 'Continue import?'.format(
                         vers['ver-app'], app.app_exe_version()),
                     app.MB_OKCANCEL)):
             return (None, None)
         mcrs = vers_mcrs.get('macros', [])
         if 0 != len(mcrs):
             break  #while
         if app.ID_OK != app.msg_box(
                 'No macros in file\n  ' + imp_file +
                 '\n\nChoose another file?', app.MB_OKCANCEL):
             return (None, None)
     #while True:
     return (imp_file, mcrs)
Example #2
0
 def dlg_import_choose_mcrs(self):
     l,lt    = '\n', '\n  '
     while True:
         imp_file= app.dlg_file(True, '', '', 'Cuda macros|*.cuda-macros|All file|*.*')
         if imp_file is None:
             return (None, None)
         vers_mcrs   = apx._json_loads(open(imp_file).read())
         if vers_mcrs is None:
             if app.ID_OK != app.msg_box('No macros in file\n  '+imp_file+'\n\nChoose another file?'
                 ,app.MB_OKCANCEL):  
                 return (None, None)
             continue #while
         vers        = vers_mcrs.get('vers', {})
         if (app.app_api_version() < vers.get('ver-api', app.app_api_version())
         and app.ID_OK != app.msg_box(
                     'Macros from'
                 +lt+imp_file    
                 +l+ 'are recorded in CudaText with version' 
                 +lt+    '"{}"'
                 +l+ 'Your CudaText has older version' 
                 +lt+    '"{}"'
                 +l+ ''
                 +l+ 'No guarantee of correct working!'
                 +l+ ''
                 +l+ 'Continue import?'.format(vers['ver-app'], app.app_exe_version())
                 ,   app.MB_OKCANCEL)):
             return (None, None)
         mcrs    = vers_mcrs.get('macros', [])
         if 0!=len(mcrs):
             break #while
         if app.ID_OK != app.msg_box('No macros in file\n  '+imp_file+'\n\nChoose another file?'
             ,app.MB_OKCANCEL):  
             return (None, None)
        #while True:
     return (imp_file, mcrs)
Example #3
0
 def do_code(self, aid, ag, data=''):
     m,M         = self,self.__class__
     
     lwks_n  = ag.cval('lwks')
     if lwks_n==-1:                      return [] #continue#while
     m.cmd_id  = m.fl_Is[lwks_n]
     pass;                  #LOG and log('m.fl_Is={}',(m.fl_Is))
     pass;                  #LOG and log('lwks_n,m.cmd_id={}',(lwks_n,m.cmd_id))
     if False:pass
     elif aid=='cpnm':
         cmd_nkk = m.id2nkks[m.cmd_id]
         app.app_proc(app.PROC_SET_CLIP, cmd_nkk[0])
     
     elif aid=='open':
         pass;               LOG and log('m.cmd_id={}',(m.cmd_id))
         if type(m.cmd_id)!=str:         return [] #continue#while
         plug_mdl,   \
         plug_mth    = m.cmd_id.split(',')[0:2]
         plug_mth    = 'def '+ plug_mth + '(self):'
         plug_dir    = app.app_path(app.APP_DIR_PY)+os.sep+plug_mdl
         plug_py     = plug_dir+os.sep+'__init__.py'
         plug_body   = open(plug_py, encoding='UTF-8').read()
         pass;               LOG and log('plug_mdl,plug_mth,plug_dir,plug_py={}',(plug_mdl,plug_mth,plug_dir,plug_py))
         mch         = re.search(r'from\s+\.(\w+)\s+import\s+Command', plug_body)
         if mch:
             # from .other_py import Command
             plug_py = plug_dir+os.sep+mch.group(1)+'.py'
             pass;           LOG and log('plug_py={}',(plug_py))
             plug_body=open(plug_py, encoding='UTF-8').read()
         if plug_mth not in plug_body:   return [] #continue#while
         # Open
         app.file_open(plug_py)
         # Locate
         user_opt= app.app_proc(app.PROC_GET_FINDER_PROP, '') \
                     if app.app_api_version()>='1.0.248' else \
                   app.app_proc(app.PROC_GET_FIND_OPTIONS, '')   # Deprecated
         ed.cmd(cmds.cmd_FinderAction, chr(1).join([]
             +['findnext']
             +[plug_mth]
             +['']
             +['fa']
         ))
         if app.app_api_version()>='1.0.248':
             app.app_proc(app.PROC_SET_FINDER_PROP, user_opt)
         else:
             app.app_proc(app.PROC_SET_FIND_OPTIONS, user_opt)   # Deprecated
         return None #break#while
     return []
 def do_code(self, aid, ag):
     m,M         = self,CfgKeysDlg
     
     lwks_n  = ag.cval('lwks')
     if lwks_n==-1:                      return [] #continue#while
     m.cmd_id  = m.fl_Is[lwks_n]
     pass;                  #LOG and log('m.fl_Is={}',(m.fl_Is))
     pass;                  #LOG and log('lwks_n,m.cmd_id={}',(lwks_n,m.cmd_id))
     if False:pass
     elif aid=='cpnm':
         cmd_nkk = m.id2nkks[m.cmd_id]
         app.app_proc(app.PROC_SET_CLIP, cmd_nkk[0])
     
     elif aid=='open':
         pass;               LOG and log('m.cmd_id={}',(m.cmd_id))
         if type(m.cmd_id)!=str:         return [] #continue#while
         plug_mdl,   \
         plug_mth    = m.cmd_id.split(',')[0:2]
         plug_mth    = 'def '+ plug_mth + '(self):'
         plug_dir    = app.app_path(app.APP_DIR_PY)+os.sep+plug_mdl
         plug_py     = plug_dir+os.sep+'__init__.py'
         plug_body   = open(plug_py, encoding='UTF-8').read()
         pass;               LOG and log('plug_mdl,plug_mth,plug_dir,plug_py={}',(plug_mdl,plug_mth,plug_dir,plug_py))
         mch         = re.search(r'from\s+\.(\w+)\s+import\s+Command', plug_body)
         if mch:
             # from .other_py import Command
             plug_py = plug_dir+os.sep+mch.group(1)+'.py'
             pass;           LOG and log('plug_py={}',(plug_py))
             plug_body=open(plug_py, encoding='UTF-8').read()
         if plug_mth not in plug_body:   return [] #continue#while
         # Open
         app.file_open(plug_py)
         # Locate
         user_opt= app.app_proc(app.PROC_GET_FINDER_PROP, '') \
                     if app.app_api_version()>='1.0.248' else \
                   app.app_proc(app.PROC_GET_FIND_OPTIONS, '')   # Deprecated
         ed.cmd(cmds.cmd_FinderAction, chr(1).join([]
             +['findnext']
             +[plug_mth]
             +['']
             +['fa']
         ))
         if app.app_api_version()>='1.0.248':
             app.app_proc(app.PROC_SET_FINDER_PROP, user_opt)
         else:
             app.app_proc(app.PROC_SET_FIND_OPTIONS, user_opt)   # Deprecated
         return None #break#while
     return []
 def __init__(self):  #NOTE: init
     if app.app_api_version() < FROM_API_VERSION:
         return app.msg_status(_('Need update application'))
     self.wrap = apx.get_opt('intextbookmk_wrap',
                             apx.get_opt('ibm_wrap', True))
     self.show_wo_alt = apx.get_opt('intextbookmk_compact_show',
                                    apx.get_opt('ibm_compact_show', True))
     #       self.show_wo_alt= apx.get_opt('intextbookmk_compact_show'    , apx.get_opt('ibm_compact_show'    , False))
     self.unlxr_cmnt = apx.get_opt(
         'intextbookmk_no_lexer_comment',
         apx.get_opt('ibm_no_lexer_comment', '//'))
     self.bm_signs = apx.get_opt(
         'intextbookmk_signs',
         apx.get_opt('ibm_signs',
                     ['NOTE:', 'NB!', 'TODO:', 'todo:', 'todo.', 'FIX:']))
     self.bm_signs = [self.bm_signs] if type(
         self.bm_signs) == str else self.bm_signs
     self.bm_sign = self.bm_signs[0]
     self.lxr2cmnt = {NO_LXR_SIGN: self.unlxr_cmnt}
     self.ext2lxr = {}
     for lxr in apx.get_enabled_lexers():
         cmnt = app.lexer_proc(app.LEXER_GET_PROP, lxr)['c_line']
         #           cmnt                    = app.lexer_proc(app.LEXER_GET_COMMENT, lxr)
         if not cmnt:
             continue  #for lxr
         self.lxr2cmnt[lxr] = cmnt
         for ext in app.lexer_proc(app.LEXER_GET_PROP, lxr)['typ']:
             self.ext2lxr[ext] = lxr
Example #6
0
    def dlg_import(self):
        ''' Show dlg for import some macros.
        '''
        if app.app_api_version()<FROM_API_VERSION:  return app.msg_status(_('Need update CudaText'))
        (imp_file
        ,mcrs)  = self.dlg_import_choose_mcrs()
        if imp_file is None:    return
        lmcrs   = len(mcrs)
        
        WD_LST, \
        HT_LST  = (500
                  ,500)
        crt,sels= '0', ['1'] * lmcrs
        while True:

            cnts    = ([
  dict(              tp='lb'    ,tid='file'         ,l=GAP             ,w=85            ,cap=_('Import &from')              )
 ,dict(cid='file'   ,tp='ed'    ,t=GAP              ,l=GAP+85          ,r=GAP+WD_LST-35 ,en='0'                             )
 ,dict(cid='brow'   ,tp='bt'    ,tid='file'         ,l=GAP+HT_LST-35   ,r=GAP+WD_LST    ,cap=_('&...')                      )
 ,dict(cid='mcrs'   ,tp='ch-lbx',t=35  ,h=HT_LST    ,l=GAP             ,w=    WD_LST    ,items=[mcr['nm'] for mcr in mcrs]  )
 ,dict(cid='ch-a'   ,tp='bt'    ,t=GAP+35+HT_LST    ,l=GAP*1           ,w=100           ,cap=_('Check &all')                )
 ,dict(cid='ch-n'   ,tp='bt'    ,t=GAP+35+HT_LST    ,l=GAP*2+100       ,w=100           ,cap=_('U&ncheck all')              )
 ,dict(cid='impo'   ,tp='bt'    ,t=GAP+35+HT_LST    ,l=    WD_LST-70*2 ,w=70            ,cap=_('&Import')       ,props='1'  )   # default
 ,dict(cid='-'      ,tp='bt'    ,t=GAP+35+HT_LST    ,l=GAP+WD_LST-70*1 ,w=70            ,cap=_('Close')                     )
                    ])
            vals    = dict( file=imp_file
                           ,mcrs=(crt, sels)
                        )
            btn,    \
            vals,   \
            chds    = dlg_wrapper(_('Import macros'), GAP+WD_LST+GAP, GAP*4+HT_LST+25*2, cnts, vals, focus_cid='mrcs')
            if btn is None or btn=='-': return
            crt,sels= vals['mcrs']
            pass;               LOG and log('sels={}',sels)
            if False:pass
            elif btn=='brow': #ans_s=='file':
                (new_imp_file
                ,new_mcrs)  = self.dlg_import_choose_mcrs()
                if new_imp_file is None:    continue #while
                imp_file    = new_imp_file
                mcrs        = new_mcrs
                lmcrs       = len(mcrs)
                crt,sels    = '0', ['1'] * lmcrs
            elif btn=='ch-a': #ans_s=='all':
                sels    = ['1'] * lmcrs
            elif btn=='ch-n': #ans_s=='no':
                sels    = ['0'] * lmcrs
            elif btn=='impo': #ans_s=='imp':
                if '1' not in sels:
                    app.msg_box(_('Select some names'), app.MB_OK)
                    continue
                (good_nms
                ,fail_nms) = self.import_from_list([mcr for (ind, mcr) in enumerate(mcrs) if sels[ind]=='1'])
                l,lt    = '\n', '\n      '
                app.msg_box(   _('Import macros:')     +lt+lt.join(good_nms)
                            +l+''
                            +l+_('Skip duplicates:')   +lt+lt.join(fail_nms)
                           ,app.MB_OK)
	def report_to_html(self):
		if app_name=='CudaText' and app.app_api_version()<'1.0.105':
			app.msg_box('Plugin needs newer app version', app.MB_OK)
			return

		htm_file = os.path.join(tempfile.gettempdir(), '{}_keymapping.html'.format(app_name))
		do_report(htm_file)
		webbrowser.open_new_tab('file://'+htm_file)
		app.msg_status('Opened browser with file '+htm_file)
Example #8
0
def dlg_menu(how, its='', sel=0, cap='', clip=0, w=0, h=0):
    api = app.app_api_version()
#   if api<='1.0.193':  #  list/tuple, focused(?), caption
#   if api<='1.0.233':  #  MENU_NO_FUZZY, MENU_NO_FULLFILTER
#   if api<='1.0.275':  #  MENU_CENTERED
    if api<='1.0.334':  #  clip, w, h
        return  app.dlg_menu(how, its, focused=sel, caption=cap)
#   if api<='1.0.346':  #  MENU_EDITORFONT
    return      app.dlg_menu(how, its, focused=sel, caption=cap, clip=clip, w=w, h=h)
Example #9
0
	def report_to_html(self):
#		if app_name=='CudaText' and app.app_api_version()<'1.0.105':
		if app_name=='CudaText' and app.app_api_version()<'1.0.212':     # depr PROC_GET_COMMAND, PROC_GET_COMMAND_PLUGIN
			app.msg_box(_('Plugin needs newer app version'), app.MB_OK)
			return

		htm_file = os.path.join(tempfile.gettempdir(), '{}_keymapping.html'.format(app_name))
		do_report(htm_file)
		webbrowser.open_new_tab('file://'+htm_file)
		app.msg_status(_('Opened browser with file ')+htm_file)
	def compact_to_tab(self):
		if app_name=='CudaText' and app.app_api_version()<'1.0.212':     # depr PROC_GET_COMMAND, PROC_GET_COMMAND_PLUGIN
			app.msg_box('Plugin needs newer app version', app.MB_OK)
			return
		plain_rpt	= get_str_report()
		if False:pass
		elif app_name=='CudaText':
			app.file_open('')
			ed.set_text_all(plain_rpt)
		elif app_name=='SynWrite':
			pass
Example #11
0
	def compact_to_tab(self):
		if app_name=='CudaText' and app.app_api_version()<'1.0.212':     # depr PROC_GET_COMMAND, PROC_GET_COMMAND_PLUGIN
			app.msg_box(_('Plugin needs newer app version'), app.MB_OK)
			return
		plain_rpt	= get_str_report()
		if False:pass
		elif app_name=='CudaText':
			app.file_open('')
			ed.set_text_all(plain_rpt)
		elif app_name=='SynWrite':
			pass
Example #12
0
 def best_path(id_prnt, prnt_cap=''):
     rsp_l   = []
     kids    = app.tree_proc(ID_TREE, app.TREE_ITEM_ENUM, id_prnt)
     pass;                  #log('>>id_prnt, prnt_cap, kids={}',(id_prnt, prnt_cap, len(kids) if kids else 0))
     if kids is None:
         pass;              #log('<<no kids',())
         return [], INF
     row_bfr, kid_bfr, cap_bfr = -INF, NO_ID, ''
     row_aft, kid_aft, cap_aft = +INF, NO_ID, ''
     for kid, cap in kids:
         pass;              #log('kid, cap={}',(kid, cap))
         cMin, rMin, \
         cMax, rMax  = app.tree_proc(ID_TREE, app.TREE_ITEM_GET_SYNTAX_RANGE , kid) \
                         if app.app_api_version() < '1.0.226' else \
                       app.tree_proc(ID_TREE, app.TREE_ITEM_GET_RANGE        , kid)
         pass;              #log('? kid,cap, rMin,rMax,row={}',(kid,cap, rMin,rMax,row))
         if False:pass
         elif rMin<=row<=rMax:   # Cover!
             sub_l, gap_sub  = best_path(kid, cap)
             pass;          #log('? sub_l, gap_sub={}',(sub_l, gap_sub))
             if gap_sub == 0:    # Sub-kid also covers
                 pass;      #log('+ sub_l={}',(sub_l))
                 rsp_l   = [(kid, cap)] + sub_l
             else:               # The kid is best
                 pass;      #log('0 ',())
                 rsp_l   = [(kid, cap)]
             pass;          #log('<<! rsp_l={}',(rsp_l))
             return rsp_l, 0
         elif row_bfr                  < rMax            < row:
             row_bfr, kid_bfr, cap_bfr = rMax, kid, cap
             pass;          #log('< row_bfr, kid_bfr, cap_bfr={}',(row_bfr, kid_bfr, cap_bfr))
         elif row_aft                  > rMin            > row:
             row_aft, kid_aft, cap_aft = rMin, kid, cap
             pass;          #log('> row_aft, kid_aft, cap_aft={}',(row_aft, kid_aft, cap_aft))
        #for kid
     pass;                  #log('? row_bfr, kid_bfr, cap_bfr={}',(row_bfr, kid_bfr, cap_bfr))
     pass;                  #log('? row_aft, kid_aft, cap_aft={}',(row_aft, kid_aft, cap_aft))
     pass;                  #log('? abs(row_bfr-row), abs(row_aft-row)={}',(abs(row_bfr-row), abs(row_aft-row)))
     kid_x, cap_x, gap_x = (kid_bfr, cap_bfr, row_bfr-row) \
                         if abs(row_bfr-row) <= abs(row_aft-row) else \
                           (kid_aft, cap_aft, row_aft-row)
     pass;                  #log('kid_x, cap_x, gap_x={}',(kid_x, cap_x, gap_x))
     sub_l, gap_sub  = best_path(kid_x, cap_x)
     pass;                  #log('? sub_l,gap_sub ?? gap_x={}',(sub_l, gap_sub, gap_x))
     if abs(gap_sub) <= abs(gap_x):  # Sub-kid better
         rsp_l  = [(kid_x, cap_x)] + sub_l
         pass;              #log('<<sub bt: rsp_l, gap_sub={}',(rsp_l, gap_sub))
         return rsp_l, gap_sub
     # The kid is best
     rsp_l   = [(kid_x, cap_x)]
     pass;                  #log('<<bst: rsp_l, gap_x={}',(rsp_l, gap_x))
     return rsp_l, gap_x
Example #13
0
    def dlg_export(self):
        ''' Show dlg for export some macros.
        '''
        if app.app_api_version()<FROM_API_VERSION:  return app.msg_status(_('Need update CudaText'))
        if 0==len(self.macros):                     return app.msg_status(_('No macros for export'))
        exp_file= app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros')
        exp_file= '' if exp_file is None else exp_file
        exp_file= exp_file+('' if ''==exp_file or exp_file.endswith('.cuda-macros') else '.cuda-macros')
        (WD_LST
        ,HT_LST)= (500
                  ,500)
        
        lmcrs   = len(self.macros)
        crt,sels= '0', ['0'] * lmcrs
        while True:
            pass;               LOG and log('sels={}',sels)

            cnts    = ([
  dict(              tp='lb'    ,tid='file'         ,l=GAP             ,w=70            ,cap=_('Export &to')                    )
 ,dict(cid='file'   ,tp='ed'    ,t=GAP              ,l=GAP+70          ,r=GAP+WD_LST-35 ,en='0'                                 )
 ,dict(cid='brow'   ,tp='bt'    ,tid='file'         ,l=GAP+HT_LST-35   ,r=GAP+WD_LST    ,cap=_('&...')                          )
 ,dict(cid='mcrs'   ,tp='ch-lbx',t=35   ,h=HT_LST   ,l=GAP             ,w=    WD_LST    ,items=[mcr['nm'] for mcr in self.macros])
 ,dict(cid='ch-a'   ,tp='bt'    ,t=GAP+35+HT_LST    ,l=GAP*1           ,w=100           ,cap=_('Check &all')                    )
 ,dict(cid='ch-n'   ,tp='bt'    ,t=GAP+35+HT_LST    ,l=GAP*2+100       ,w=100           ,cap=_('U&ncheck all')                  )
 ,dict(cid='expo'   ,tp='bt'    ,t=GAP+35+HT_LST    ,l=    WD_LST-70*2 ,w=70            ,cap=_('&Export')       ,props='1'      )   # default
 ,dict(cid='-'      ,tp='bt'    ,t=GAP+35+HT_LST    ,l=GAP+WD_LST-70*1 ,w=70            ,cap=_('Close')                         )
                    ])
            vals    = dict( file=exp_file
                           ,mcrs=(crt, sels)
                        )
            btn,    \
            vals,   \
            chds    = dlg_wrapper(_('Export macros')   ,GAP+WD_LST+GAP, GAP*5+HT_LST+25*2-GAP, cnts, vals, focus_cid='mrcs')
            if btn is None or btn=='-': return
            crt,sels= vals['mcrs']
            pass;               LOG and log('sels={}',sels)
            if False:pass
            elif btn=='brow': #ans_s=='file':
                new_exp_file= app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros')
                if new_exp_file is not None:
                    exp_file    = new_exp_file
                    exp_file    = exp_file+('' if ''==exp_file or exp_file.endswith('.cuda-macros') else '.cuda-macros')
            elif btn=='ch-a': #ans_s=='all':
                sels    = ['1'] * lmcrs
            elif btn=='ch-n': #ans_s=='no':
                sels    = ['0'] * lmcrs
            elif btn=='expo': #ans_s=='exp':
                if '1' not in sels:
                    app.msg_box(_('Select some names'), app.MB_OK)
                    continue
                self.export_to_file(exp_file, [mcr for (ind, mcr) in enumerate(self.macros) if sels[ind]=='1'])
                return
 def recent(self):
     ''' Show list, use user select '''
     if not _checkAPI(): return
     sess = self._loadSess(existing=True)
     rcnt = sess['recent']
     if 0 == len(rcnt):
         return app.msg_status(NO_RECENT)
     ssmenu = [nice_name(sfile) for sfile in rcnt]
     opt_n = 0 if app.app_api_version(
     ) < '1.0.233' else app.MENU_NO_FULLFILTER
     ans = app.dlg_menu(app.MENU_LIST + opt_n, ssmenu)
     if ans is None: return
     self.open(rcnt[ans])
 def show_list(self, wdex):
     if app.app_api_version()<'1.0.144': return app.msg_status(_('Need update CudaText'))
     if not self._prep_sess(wdex): return
     if not self.sess.bids:
         return app.msg_status(_('No in-text completions'))
     if self.sngl and 1==len(self.sess.bids):
         return self._subst('#0', 'curr')
     ed.complete_alt(c10.join([bd.replace(c9, '¬')                   # main text
                             +c9+f(':{}', 1+self.sess.bids_c[ibd])   # right text ":row"
                             +c9+str(ibd)                            # hidden text
                             for (ibd, bd) in enumerate(self.sess.bids)])
                    ,'in-te-co', 0
                    ,self.sess.bids_i)
Example #16
0
 def export_to_file(self, exp_file, mcrs):
     pass;                   LOG and log('exp_file, mcrs={}',(exp_file, mcrs))
     open(exp_file, 'w').write(json.dumps(
         {   'vers':{
                 'ver-mcr':JSON_FORMAT_VER
             ,   'ver-app':app.app_exe_version()
             ,   'ver-api':app.app_api_version()
             }
         ,   'macros':[{
                 'nm':   mcr['nm']
              ,  'evl':  mcr['evl']
                 } for mcr in mcrs]
         }
     ,   indent=4))
Example #17
0
def go_back_tab():
    if app.app_api_version() < '1.0.253':
        return app.msg_status(NEED_UPDATE)
    pass
    #log("###",( ))
    eds = [app.Editor(h) for h in app.ed_handles()]  # Native order
    ed_tats = [(ed_, ed_.get_prop(app.PROP_ACTIVATION_TIME, ''))
               for ed_ in eds]
    ed_tats = [(at, ed_) for (ed_, at) in ed_tats if at]  # Only activated
    if len(ed_tats) < 2:
        return app.msg_status(_('No yet other activated tab'))
    ed_tats.sort(reverse=True, key=lambda ae: ae[0])
    ed_back = ed_tats[1][1]
    ed_back.focus()
Example #18
0
 def export_to_file(self, exp_file, mcrs):
     pass
     LOG and log('exp_file, mcrs={}', (exp_file, mcrs))
     open(exp_file, 'w').write(
         json.dumps(
             {
                 'vers': {
                     'ver-mcr': JSON_FORMAT_VER,
                     'ver-app': app.app_exe_version(),
                     'ver-api': app.app_api_version()
                 },
                 'macros': [{
                     'nm': mcr['nm'],
                     'evl': mcr['evl']
                 } for mcr in mcrs]
             },
             indent=4))
Example #19
0
def close_tab_from_other_group(what_grp='next'):
    if app.app_api_version() < '1.0.139': return app.msg_status(NEED_UPDATE)
    grps = apx.get_groups_count()
    if 1 == grps: return
    me_grp = ed.get_prop(app.PROP_INDEX_GROUP)
    cl_grp  = (me_grp+1)%grps \
                if what_grp=='next' else \
              (me_grp-1)%grps
    if not [
            h for h in app.ed_handles()
            if app.Editor(h).get_prop(app.PROP_INDEX_GROUP) == cl_grp
    ]:
        return app.msg_status(_('No files in group'))
    cl_ed = app.ed_group(cl_grp)
    cl_ed.focus()
    cl_ed.cmd(cmds.cmd_FileClose)
    me_ed = app.ed_group(me_grp)
    me_ed.focus()
 def show_list(self, wdex):
     if app.app_api_version() < '1.0.144':
         return app.msg_status(_('Need update CudaText'))
     if not self._prep_sess(wdex): return
     if not self.sess.bids:
         return app.msg_status(_('No in-text completions'))
     if self.sngl and 1 == len(self.sess.bids):
         return self._subst('#0', 'curr')
     ed.complete_alt(
         c10.join([
             bd.replace(c9, '¬')  # main text
             + c9 + f(':{}', 1 + self.sess.bids_c[ibd])  # right text ":row"
             + c9 + str(ibd)  # hidden text
             for (ibd, bd) in enumerate(self.sess.bids)
         ]),
         'in-te-co',
         0,
         self.sess.bids_i)
    def __init__(self):#NOTE: init
        if app.app_api_version()<FROM_API_VERSION:  return app.msg_status(_('Need update application'))
        self.wrap       = apx.get_opt('intextbookmk_wrap'            , apx.get_opt('ibm_wrap'            , True))
        self.show_wo_alt= apx.get_opt('intextbookmk_compact_show'    , apx.get_opt('ibm_compact_show'    , True))
#       self.show_wo_alt= apx.get_opt('intextbookmk_compact_show'    , apx.get_opt('ibm_compact_show'    , False))
        self.unlxr_cmnt = apx.get_opt('intextbookmk_no_lexer_comment', apx.get_opt('ibm_no_lexer_comment', '//'))
        self.bm_signs   = apx.get_opt('intextbookmk_signs'           , apx.get_opt('ibm_signs'           , ['NOTE:', 'NB!', 'TODO:', 'todo:', 'todo.', 'FIX:']))
        self.bm_signs   = [self.bm_signs] if type(self.bm_signs)==str else self.bm_signs
        self.bm_sign    = self.bm_signs[0]
        self.lxr2cmnt   = {NO_LXR_SIGN:self.unlxr_cmnt}
        self.ext2lxr    = {}
        for lxr in apx.get_enabled_lexers():
            cmnt                    = app.lexer_proc(app.LEXER_GET_PROP, lxr)['c_line']
#           cmnt                    = app.lexer_proc(app.LEXER_GET_COMMENT, lxr)
            if not cmnt:
                continue#for lxr
            self.lxr2cmnt[lxr]      = cmnt
            for ext in app.lexer_proc(app.LEXER_GET_PROP, lxr)['typ']:
                self.ext2lxr[ext]   = lxr
Example #22
0
def _check_API(ver):
    if app.app_api_version() < ver:
        app.msg_status(NEED_NEWER_API)
        return False
    return True
def _checkAPI():
    if app.app_api_version()<'1.0.106':
        app.msg_status(NEED_NEWER_API)
        return False
    return True
Example #24
0
    def dlg_config(self):
        ''' Show dlg for change macros list.
        '''
        if app.app_api_version()<FROM_API_VERSION:  return app.msg_status(_('Need update CudaText'))
        keys_json   = app.app_path(app.APP_DIR_SETTINGS)+os.sep+'keys.json'
        keys        = apx._json_loads(open(keys_json).read()) if os.path.exists(keys_json) else {}
        
        ids     = [mcr['id'] for mcr in self.macros]
        mcr_ind = ids.index(self.last_mcr_id) if self.last_mcr_id in ids else -1
        pass;                   LOG and log('self.last_mcr_id, mcr_ind={}',(self.last_mcr_id,mcr_ind))
        times   = 1
        waits   = 5
        chngs   = '0'
        endln   = '0'
        while True:
            WD_LST, \
            HT_LST  = (self.dlg_prs.get('w_list', 300)
                      ,self.dlg_prs.get('h_list', 500))
            WD_ACTS,\
            HT_ACTS = (self.dlg_prs.get('w_acts', 300)
                      ,self.dlg_prs.get('h_acts', 500))
            WD_BTN, \
            HT_BTN  = (self.dlg_prs.get('w_btn', 150), 24)
            WD_BTN_3= int(WD_BTN/3)
            l_btn   = GAP+WD_LST+GAP
            l_acts  = GAP+WD_LST+GAP+WD_BTN+GAP
            
            vw_acts = (WD_ACTS>0)
            WD_ACTS = max(0, WD_ACTS)
            rec_on  = ed.get_prop(app.PROP_MACRO_REC)
            lmcrs   = len(self.macros)
            pass;               LOG and log('mcr_ind,vw_acts,rec_on={}',(mcr_ind,vw_acts,rec_on))

            nmkys   = []
            for mcr in self.macros:
                mcr_cid = 'cuda_macros,run,{}'.format(mcr['id'])
                mcr_keys= keys.get(mcr_cid, {})
                kys     = '/'.join([' * '.join(mcr_keys.get('s1', []))
                                   ,' * '.join(mcr_keys.get('s2', []))
                                   ]).strip('/')
                nmkys  += [mcr['nm'] + (' ['+kys+']' if kys else '')]

            mcr_acts= ['']
#           mcr_acts= ''
            if vw_acts and mcr_ind in range(lmcrs):
                mcr     = self.macros[mcr_ind]
                mcr_acts=           ['# '+nmkys[mcr_ind]] + mcr['evl']
#               mcr_acts= '\t'.join(['# '+nmkys[mcr_ind]] + mcr['evl'])

            def_stst    = '1' if                     rec_on or 0==lmcrs else '0'
            n_edable    = '0' if                     rec_on or 0==lmcrs else '1'
            n_vwable    = '1' if not vw_acts and not rec_on else '0'
            only_rec_off= '0' if                     rec_on else '1'
            only_rec_on = '1' if                     rec_on else '0'
            tims_props  = '0,{},1'.format(self.dlg_prs.get('times',  1000))
            stst_cap    = _('&Stop record') if       rec_on else _('&Start record')
            cnts        = ([]
 +[dict(cid='mrcs'   ,tp='lbx'  ,t=GAP  ,h=HT_LST       ,l=GAP                  ,w=WD_LST   ,items=nmkys                            ,en=only_rec_off    )]
 +(                                                                                                     
  [dict(cid='view'   ,tp='bt'   ,t=GAP* 1+HT_BTN* 0     ,l=l_btn                ,w=WD_BTN   ,cap=_('&View actions') ,props=n_edable,en=n_edable         )]  # default
  if vw_acts else [])                                                                                     
 +[dict(cid='keys'   ,tp='bt'   ,t=GAP* 2+HT_BTN* 1     ,l=l_btn                ,w=WD_BTN   ,cap=_('Hot&keys...')                   ,en=n_edable        )]
 +[dict(cid='renm'   ,tp='bt'   ,t=GAP* 3+HT_BTN* 2     ,l=l_btn                ,w=WD_BTN   ,cap=_('Re&name...')                    ,en=n_edable        )]
 +[dict(cid='del'    ,tp='bt'   ,t=GAP* 4+HT_BTN* 3     ,l=l_btn                ,w=WD_BTN   ,cap=_('&Delete...')                    ,en=n_edable        )]
 +[dict(cid='run'    ,tp='bt'   ,t=GAP* 6+HT_BTN* 5     ,l=l_btn                ,w=WD_BTN   ,cap=_('&Run!')         ,props=n_vwable ,en=n_edable        )]  # default
 +[dict(              tp='lb'   ,tid='times'            ,l=l_btn                ,w=WD_BTN_3 ,cap=_('&Times')                                            )]
 +[dict(cid='times'  ,tp='sp-ed',t=GAP* 7+HT_BTN* 6     ,l=l_btn+WD_BTN_3+GAP   ,r=l_btn+WD_BTN                     ,props=tims_props,en=only_rec_off   )]  # min,max,step
 +[dict(              tp='lb'   ,tid='waits'            ,l=l_btn                ,w=WD_BTN_3 ,cap=_('&Wait')                                             )]
 +[dict(cid='waits'  ,tp='sp-ed',t=GAP* 8+HT_BTN* 7     ,l=l_btn+WD_BTN_3+GAP   ,r=l_btn+WD_BTN-40                  ,props='1,3600,1',en=only_rec_off   )]  # min,max,step
 +[dict(              tp='lb'   ,tid='waits'            ,l=l_btn+WD_BTN-40+GAP  ,w=WD_BTN   ,cap=_('sec')                                               )]
 +[dict(cid='chngs'  ,tp='ch'   ,t=GAP* 9+HT_BTN* 8     ,l=l_btn                ,w=WD_BTN   ,cap=_('While text c&hanges')                               )]
 +[dict(cid='endln'  ,tp='ch'   ,t=GAP*10+HT_BTN* 9     ,l=l_btn                ,w=WD_BTN   ,cap=_('Until c&aret on last line')                         )]
 +[dict(cid='stst'   ,tp='bt'   ,t=GAP*12+HT_BTN*11     ,l=l_btn                ,w=WD_BTN   ,cap=stst_cap           ,props=def_stst                     )]
 +[dict(cid='canc'   ,tp='bt'   ,t=GAP*13+HT_BTN*12     ,l=l_btn                ,w=WD_BTN   ,cap=_('Canc&el record')                ,en=only_rec_on     )]
 +[dict(cid='adju'   ,tp='bt'   ,t=    HT_LST-HT_BTN*2  ,l=l_btn                ,w=WD_BTN   ,cap=_('Ad&just...')                    ,en=only_rec_off    )]
 +[dict(cid='-'      ,tp='bt'   ,t=GAP+HT_LST-HT_BTN*1  ,l=l_btn                ,w=WD_BTN   ,cap=_('Close')                                             )]
 +(
  [dict(cid='acts'   ,tp='me'   ,t=GAP  ,h=HT_ACTS      ,l=l_acts               ,w=WD_ACTS                          ,props='1,1,1'                      )]  # ro,mono,border
  if vw_acts else [])
                    )
            vals    = dict( mrcs=mcr_ind
                           ,times=times
                           ,waits=waits
                           ,chngs=chngs
                           ,endln=endln
                        )
            if vw_acts: vals.update(
                      dict( acts=mcr_acts
                        ))
            btn,    \
            vals,   \
            chds    = dlg_wrapper(_('Macros'), GAP+WD_LST+GAP+WD_BTN+GAP+WD_ACTS+GAP,GAP+HT_LST+GAP, cnts, vals, focus_cid='mrcs')
            if btn is None or btn=='-': return
            mcr_ind = vals['mrcs']
            times   = vals['times']
            waits   = vals['waits']
            chngs   = vals['chngs']
            endln   = vals['endln']
            pass;               LOG and log('mcr_ind,times,waits,chngs,endln={}',(mcr_ind,times,waits,chngs,endln))

            if 0!=lmcrs and mcr_ind in range(lmcrs):
                mcr     = self.macros[mcr_ind]
                self.last_mcr_id = mcr['id']
            
#           if ans_s=='close':  break #while
            if btn=='adju': #ans_s=='custom': #Custom
                custs   = app.dlg_input_ex(5, _('Custom dialog Macros')
                    , _('Height of macro list (min 450)')          , str(self.dlg_prs.get('h_list', 400))
                    , _('Width of macro list (min 200)')           , str(self.dlg_prs.get('w_list', 500))
                    , _('Width of action list (min 200, <=0-hide)'), str(self.dlg_prs.get('w_acts', 500))
                    , _('Width of buttons (min 150)')              , str(self.dlg_prs.get('w_btn',  150))
                    , _('Max run times (min 100)')                 , str(self.dlg_prs.get('times',  1000))
                    )
                if custs is not None:
                    self.dlg_prs['h_list']  = max(450, int(custs[0]));  self.dlg_prs['h_acts'] = self.dlg_prs['h_list']
                    self.dlg_prs['w_list']  = max(200, int(custs[1]))
                    self.dlg_prs['w_acts']  = max(200, int(custs[2])) if int(custs[2])>0 else int(custs[2])
                    self.dlg_prs['w_btn']   = max(150, int(custs[3]))
                    self.dlg_prs['times']   = max(100, int(custs[4]))
                    open(MACROS_JSON, 'w').write(json.dumps({'ver':JSON_FORMAT_VER, 'list':self.macros, 'dlg_prs':self.dlg_prs}, indent=4))
                continue #while
            
            if mcr_ind not in range(lmcrs):
                app.msg_box(_('Select macro'), app.MB_OK)
                continue #while
            
            what    = ''
            changed = False
            if False:pass
                
            elif btn=='view': #ans_s=='view': #View
                continue #while

            elif btn=='renm': #ans_s=='rename': #Rename
                mcr_nm      = app.dlg_input(_('New name for: {}').format(nmkys[mcr_ind])
                                           ,mcr['nm'])
                if mcr_nm is None or mcr_nm==mcr['nm']:     continue #while
                while mcr_nm in [mcr['nm'] for mcr in self.macros]:
                    app.msg_box(_('Select other name.\nMacro names now are:\n\n')+'\n'.join(nmkys), app.MB_OK)
                    mcr_nm  = app.dlg_input(_('New name for: {}').format(nmkys[mcr_ind])
                                           ,mcr_nm)
                    if mcr_nm is None or mcr_nm==mcr['nm']: break #while mcr_nm
                if mcr_nm is None or mcr_nm==mcr['nm']:     continue #while
                what        = 'rename'
                mcr['nm']   = mcr_nm
                changed = True
                
            elif btn=='del': #ans_s=='delete': #Del
                if app.msg_box( _('Delete macro\n    {}').format(nmkys[mcr_ind])
                              , app.MB_YESNO)!=app.ID_YES:  continue #while
                what    = 'delete:'+str(mcr['id'])
                del self.macros[mcr_ind]
                mcr_ind = min(mcr_ind, len(self.macros)-1)
                changed = True
                
            elif btn=='keys': #ans_s=='hotkeys': #Hotkeys
                app.dlg_hotkeys('cuda_macros,run,'+str(mcr['id']))
                keys    = apx._json_loads(open(keys_json).read()) if os.path.exists(keys_json) else {}
                changed = True

            elif btn=='run': #ans_s=='run': #Run
                if (times==0 
                and waits==0
                and chngs=='0'
                and endln=='0'):
                    app.msg_box(_('Select stop condition'), app.MB_OK)
                    continue
                self.run(mcr['id'], max(0, times), max(0, waits), chngs=='1', endln=='1')
                return

            elif btn=='stst'     and not rec_on: #Start record
#           elif ans_s=='rec'    and not rec_on: #Start record
                return ed.cmd(cmds.cmd_MacroStart)
            elif btn=='stst'     and     rec_on: #Stop record
#           elif ans_s=='rec'    and     rec_on: #Stop record
                self.need_dlg = True
                return ed.cmd(cmds.cmd_MacroStop)       # Return for clear rec-mode in StatusBar, will recall from on_macro
            elif btn=='canc'     and     rec_on: #Cancel record
#           elif ans_s=='cancel' and     rec_on: #Cancel record
                return ed.cmd(cmds.cmd_MacroCancel)     # Return for clear rec-mode in StatusBar
                
            if changed:
                self._do_acts(what)
Example #25
0
def collect_data():
	''' Collect data
	'''
	keys2nms	= {}
	has_series	= False
	dblkeys		= []
	ctgs		= []
	cmdinfos	= []

	if app_name=='CudaText' and app.app_api_version()>='1.0.212':
		lcmds   = app.app_proc(app.PROC_GET_COMMANDS, '')
		cmdinfos= [(_('Commands')
				   ,cmd['name']
				   ,cmd['key1']
				   ,cmd['key2']
				   #,cmd['cmd']
				   )
						if cmd['type']=='cmd' else 
				   (_('Plugins')
				   ,cmd['name']
				   ,cmd['key1']
				   ,cmd['key2']
				   #,'{},{},{}'.format(cmd['p_module'], cmd['p_method'], cmd['p_method_params']).rstrip(',')
				   )
						for cmd in lcmds
						if cmd['type']!='lexer'
				]
	else: # Syn or old Cud
		n=0
		while True:
			# Cud (5	  ,'smth', 'Shift+Ctrl+F1', 'Alt+Q * Ctrl+T')
			# Syn (5,'ctg','smth', 'Shift+Ctrl+F1', 'Alt+Q · Ctrl+T')
			cmdinfo = app.app_proc(app.PROC_GET_COMMAND, str(n))
			n += 1
			if cmdinfo is None: break
			if cmdinfo[0]<=0: continue
			if app_name=='CudaText':
				# Add default category
				cmdinfo	= (_('Commands'), cmdinfo[1], cmdinfo[2], cmdinfo[3])
			else:
				cmdinfo	= (cmdinfo[1], cmdinfo[2], cmdinfo[3], cmdinfo[4])

			ctg, name, keys1, keys2 = cmdinfo
			if	name.startswith('lexer:'):		continue	# ?? lexer? smth-more?
			if (app_name=='CudaText' and
				name.startswith('plugin:')):	continue	# ?? plugin? smth-more?
			if (app_name=='SynWrite' and
				ctg=='Plugin'):
				cmdinfo	= (ctg, _('Plugin: ')+name, keys1, keys2)

			cmdinfos += [cmdinfo]
		if app_name=='CudaText':
			cmdinfos = add_cud_plugins(cmdinfos, 'plugin: ', _('Plugins'))

	for ctg, name, keys1, keys2 in cmdinfos:
		if ctg not in ctgs:
			ctgs += [ctg]
		for keys in (keys1, keys2):
			if not keys: continue
			if srs_dlm in keys:
				# Series: Alt+Q * Ctrl+T
				# It will be parsed later when all single keys are done
				has_series = True
				continue # see Repeat...
			else:
				btn	= ('+'+keys).split('+')[-1]					# 'B' 			 	from 'Shift+Ctrl+B'
				save_btn_mod_name(
					btn
				,	keys[:-len(btn)].rstrip('+')				# 'Shift+Ctrl'		from 'Shift+Ctrl+B'
				,	name, keys
				,	mods, btns, keys2nms, dblkeys
				)

	# Repeat to parse series
	for ctg, name, keys1, keys2 in cmdinfos:
		for keys in (keys1, keys2):
			if srs_dlm not in keys: continue
			# Series: Alt+Q * Ctrl+T
			# 1. Check a conflict with head
			#	(Alt+)(Q)
			keys_hd  = keys.split(srs_dlm)[0]					# 'Alt+Q'			from 'Alt+Q * Ctrl+T'
			if keys_hd in keys2nms:
				# Conflict!
				dblkeys 			+= [keys_hd]
				keys2nms[keys_hd]	+= [name]
			# 2. Save as
			#	(Alt+Q * Ctrl+)(T)
			btn	= ('+'+keys.split(srs_dlm)[-1]).split('+')[-1]	# 'T' 				from 'Alt+Q * Ctrl+T' or 'Alt+Q * T'
			save_btn_mod_name(
				btn
			,	keys[:-len(btn)].rstrip('+')					# 'Alt+Q * Ctrl'	from 'Alt+Q * Ctrl+T'
			,	name, keys
			,	mods, btns, keys2nms, dblkeys
			)
	
	return 	(keys2nms
			,has_series
			,dblkeys
			,ctgs
			,cmdinfos)
Example #26
0
def go_back_dlg():
    pass
    log4fun = 0  # Order log in the function
    if app.app_api_version() < '1.0.253':
        return app.msg_status(NEED_UPDATE)
    pass
    log__("", (), __=(log4fun, _log4mod))
    #   scam    = app.app_proc(app.PROC_GET_KEYSTATE, '')
    if 'c' not in app.app_proc(app.PROC_GET_KEYSTATE,
                               ''):  # User already is released Ctrl
        return go_back_tab()
    cfg_keys = get_plugcmd_hotkeys('go_back_dlg')
    pass
    #log('ok scam,cfg_keys={}',(scam,cfg_keys))
    act_clr = rgb_to_int(232, 232, 232)
    pss_clr = rgb_to_int(216, 216, 216)

    side_pns = app.app_proc(app.PROC_SIDEPANEL_ENUM, '').split('\n')
    botm_pns = app.app_proc(app.PROC_BOTTOMPANEL_ENUM, '').split('\n')
    panels      = [((app.PROC_SIDEPANEL_ACTIVATE,  (pn,True)), pn)  for pn in side_pns] \
                + [( None                                    , '')                    ] \
                + [((app.PROC_BOTTOMPANEL_ACTIVATE,(pn,True)), pn)  for pn in botm_pns]
    panels = [(act, pn) for (act, pn) in panels if pn != 'Menu']
    eds = [app.Editor(h) for h in app.ed_handles()]  # Native order
    ed_tats = [(ed_, ed_.get_prop(app.PROP_ACTIVATION_TIME, ''))
               for ed_ in eds]
    ed_tats = [(at, ed_) for (ed_, at) in ed_tats if at]  # Only activated
    ed_tats.sort(reverse=True, key=lambda ae: ae[0])
    eds = [ed_ for (at, ed_) in ed_tats]  # Sorted by activation time
    eds = eds[:apx.get_opt('ui_max_history_edits', 20)]  # Cut olds
    eds = eds if eds else [ed]
    eds_hist = [(ed_, ed_.get_prop(app.PROP_TAB_ID, ''),
                 ed_.get_prop(app.PROP_TAB_TITLE), ed_.get_filename())
                for ed_ in eds]
    pass
    #log('eds_hist={}',(eds_hist))
    start_sel = min(1, len(eds_hist) - 1)
    pass
    #log('start_sel,len(eds_hist)={}',(start_sel,len(eds_hist)))
    ed_back = eds_hist[start_sel][0]
    panel_to = None
    start_pnls = get_hist('switcher.start_panel', 'Code tree')

    def do_show(ag, key, data=None):
        pass
        log__("", (), __=(log4fun, _log4mod))

        if 'c' not in app.app_proc(app.PROC_GET_KEYSTATE, ''): ag.hide()
        app.timer_proc(
            app.TIMER_START_ONE, lambda tag: ag.hide()
            if 'c' not in app.app_proc(app.PROC_GET_KEYSTATE, '') else 0, 200)
        return []

    #def do_show

    def do_key_up(ag, key, data=None):
        scam = data if data is not None else app.app_proc(
            app.PROC_GET_KEYSTATE, '')
        return None if 'c' not in scam else []

    #def do_key_up

    def do_key_down(ag, key, data=None):
        nonlocal ed_back, panel_to
        scam = data if data is not None else app.app_proc(
            app.PROC_GET_KEYSTATE, '')
        pass
        #log('scam={}',(scam))
        k2K = dict(s='Shift+', c='Ctrl+', a='Alt+')
        hotkey = ''.join(k2K[k] for k in scam) + chr(key)
        pass
        #log('key,hotkey,cfg_keys={}',(key,hotkey,cfg_keys))
        to_othr = False
        sel_to = ''
        if 0: pass
        elif key == VK_ENTER: ag.hide()
        elif key == VK_ESCAPE:
            panel_to = ed_back = None
            ag.hide()

        elif key in (VK_LEFT, VK_RIGHT):
            to_othr = True

        elif key == VK_DOWN:
            sel_to = 'next'
        elif key == VK_UP:
            sel_to = 'prev'
        elif key == VK_TAB and scam == 'c':
            sel_to = 'next'
        elif key == VK_TAB and scam == 'sc':
            sel_to = 'prev'
        elif hotkey in cfg_keys:
            sel_to = 'next'
        else:
            return []
        pass
        #log('sel_to,to_othr={}',(sel_to,to_othr))

        fid = ag.focused()
        if to_othr:
            fid = 'pnls' if fid == 'tabs' else 'tabs'
            ag.update(
                dict(fid=fid,
                     ctrls=[
                         ('tabs',
                          dict(color=act_clr if fid == 'tabs' else pss_clr)),
                         ('pnls',
                          dict(color=act_clr if fid == 'pnls' else pss_clr))
                     ]))
            ed_back = None if fid == 'pnls' else eds_hist[ag.val('tabs')][0]
            panel_to = None if fid == 'tabs' else panels[ag.val('pnls')]

        pass
        #log('sel_to={}',(sel_to))
        if sel_to:
            ed_back = None
            panel_to = None
            shft = 1 if sel_to == 'next' else -1
            if fid == 'tabs':
                sel = (ag.val('tabs') + shft) % len(eds_hist)
                pass
                #log("shft,tabs.val,sel={}",(shft,ag.val('tabs'),sel))
                ed_back = eds_hist[sel][0]
                pass
                #log('sel={}',(ag.val('tabs'), sel))
                ag.update({'vals': {'tabs': sel}})
            if fid == 'pnls':
                sel = (ag.val('pnls') + shft) % len(panels)
                panel_to = panels[sel]
                if not panel_to[0]:
                    sel = (sel + shft) % len(panels)
                    panel_to = panels[sel]
                pass
                #log('sel={}',(ag.val('pnls'), sel))
                ag.update({'vals': {'pnls': sel}})

        return False  # Stop event

    #def do_key_down

    def do_select(ag, aid, data=''):
        nonlocal ed_back, panel_to
        sel = ag.val(aid)
        pass
        #log('sel={}',(sel))
        if aid == 'tabs':
            ed_back = eds_hist[sel][0]
            panel_to = None
        if aid == 'pnls':
            ed_back = None
            panel_to = panels[sel]
        return []

    def do_dclk(ag, aid, data=''):
        do_select(ag, aid)
        if aid == 'pnls' and not panel_to[0]:
            return []  # Ignore
        return None  # Close dlg

    #def do_dclk

    panls = [(pn if pn else '—' * 100) for act, pn in panels]
    items = [ed_tit for (ed_, ed_tid, ed_tit, ed_fn) in eds_hist]
    if 'c' not in app.app_proc(app.PROC_GET_KEYSTATE,
                               ''):  # User already is released Ctrl
        return go_back_tab()
    ag_swch = DlgAg(
        form=dict(cap=_('Switcher'),
                  w=350,
                  h=300,
                  frame='resize',
                  on_show=do_show,
                  on_key_down=do_key_down,
                  on_key_up=do_key_up),
        ctrls=[
            0,
            ('tabs',
             dict(tp='libx',
                  items=items,
                  ali=ALI_CL,
                  color=act_clr,
                  on=do_select,
                  on_click_dbl=do_dclk,
                  on_click=do_dclk)),
            ('pnls',
             dict(tp='libx',
                  items=panls,
                  ali=ALI_RT,
                  w=110,
                  color=pss_clr,
                  on=do_select,
                  on_click_dbl=do_dclk,
                  on_click=do_dclk))
        ][1:],
        fid='tabs',
        vals=dict(tabs=start_sel,
                  pnls=panls.index(start_pnls) if start_pnls in panls else 0))
    #   ag_swch.gen_repro_code('repro_dlg_switcher.py')
    pass
    #log("app.app_proc(app.PROC_GET_KEYSTATE, '')={}",(app.app_proc(app.PROC_GET_KEYSTATE, '')))
    if 'c' not in app.app_proc(app.PROC_GET_KEYSTATE,
                               ''):  # User already is released Ctrl
        return go_back_tab()
    ag_swch.show()
    pass
    #log("",())
    if ed_back:
        ed_back.focus()
    elif panel_to and panel_to[0]:
        set_hist('switcher.start_panel', panel_to[1])
        app.app_proc(*(panel_to[0]))
def _checkAPI():
    if app.app_api_version() < '1.0.106':
        app.msg_status(NEED_NEWER_API)
        return False
    return True
Example #28
0
    def dlg_import(self):
        ''' Show dlg for import some macros.
        '''
        if app.app_api_version() < FROM_API_VERSION:
            return app.msg_status('Need update CudaText')
        (imp_file, mcrs) = self.dlg_import_choose_mcrs()
        if imp_file is None: return
        lmcrs = len(mcrs)

        GAP = 5
        (WD_LST, HT_LST) = (500, 500)
        crt, sels = '0', ['1'] * lmcrs
        while True:
            ans = app.dlg_custom(
                'Import macros',
                GAP + WD_LST + GAP,
                GAP * 5 + HT_LST + 25 * 2,
                '\n'.join([] + [
                    C1.join([
                        'type=label',
                        POS_FMT(l=GAP, t=GAP + 3, r=GAP +
                                85, b=0), 'cap=Import &from'
                    ]  # i=0
                            )
                ] + [
                    C1.join([
                        'type=edit',
                        POS_FMT(l=GAP + 85, t=GAP, r=GAP + WD_LST -
                                35, b=0), 'val={}'.format(imp_file)
                    ]  # i=1
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=GAP + HT_LST - 35,
                                t=GAP - 2,
                                r=GAP + WD_LST,
                                b=0), 'cap=&...'
                    ]  # i=2
                            )
                ] + [
                    C1.join([
                        'type=checklistbox',
                        POS_FMT(l=GAP,
                                t=GAP * 2 + 30,
                                r=GAP + WD_LST,
                                b=GAP + 25 + HT_LST), 'items=' +
                        '\t'.join([mcr['nm'] for mcr in mcrs]), 'val=' + crt +
                        ';' + ','.join(sels)
                    ]  # i=3
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=GAP * 1,
                                t=GAP * 3 + 25 + HT_LST,
                                r=GAP * 1 + 80 * 1,
                                b=0), 'cap=Check &all'
                    ]  # i=4
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=GAP * 2 + 80,
                                t=GAP * 3 + 25 + HT_LST,
                                r=GAP * 2 + 80 * 2,
                                b=0), 'cap=U&ncheck all'
                    ]  # i=5
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=WD_LST - 60 * 2,
                                t=GAP * 3 + 25 + HT_LST,
                                r=WD_LST - 60 * 1,
                                b=0), 'cap=&Import'
                    ]  # i=6
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=GAP + WD_LST - 60 * 1,
                                t=GAP * 3 + 25 + HT_LST,
                                r=GAP + WD_LST - 60 * 0,
                                b=0), 'cap=&Close'
                    ]  # i=7
                            )
                ]),
                3)  # start focus
            pass
            LOG and log('ans={}', ans)
            if ans is None: break  #while
            (ans_i, vals) = ans
            ans_s = apx.icase(False, '', ans_i == 2, 'file', ans_i == 4, 'all',
                              ans_i == 5, 'no', ans_i == 6, 'imp', ans_i == 7,
                              'close')
            if ans_s == 'close': break  #while
            v_3 = vals.splitlines()[3]
            crt, sels = v_3.split(';')
            sels = sels.strip(',').split(',')
            pass
            LOG and log('sels={}', sels)
            if False: pass
            elif ans_s == 'file':
                (new_imp_file, new_mcrs) = self.dlg_import_choose_mcrs()
                if new_imp_file is None: continue  #while
                imp_file = new_imp_file
                mcrs = new_mcrs
                lmcrs = len(mcrs)
                crt, sels = '0', ['1'] * lmcrs
            elif ans_s == 'all':
                sels = ['1'] * lmcrs
            elif ans_s == 'no':
                sels = ['0'] * lmcrs
            elif ans_s == 'imp':
                if '1' not in sels:
                    app.msg_box('Select some names', app.MB_OK)
                    continue
                (good_nms, fail_nms) = self.import_from_list([
                    mcr for (ind, mcr) in enumerate(mcrs) if sels[ind] == '1'
                ])
                l, lt = '\n', '\n      '
                app.msg_box(
                    'Import macros:' + lt + lt.join(good_nms) + l + '' + l +
                    'Skip duplicates:' + lt + lt.join(fail_nms), app.MB_OK)
Example #29
0
def symbol_menu_levels(levels=0):
    pass;                       log4fun=-1== 1  # Order log in the function
    if  app.app_api_version() >= '1.0.277' and \
        ed.get_prop(app.PROP_CODETREE_MODIFIED_VERSION) < ed.get_prop(app.PROP_MODIFIED_VERSION):
        ed.cmd(cmds.cmd_TreeUpdate)
    h_tree = app.app_proc(app.PROC_GET_CODETREE, '')
        
    def tree_items_to_list(props=None, id_node=0, prefix='', more_levels=1000):
        '''Get all tree nodes to "props" starting from id_node (e.g. 0)'''
        props = [] if props is None else props 
        nodes = app.tree_proc(h_tree, app.TREE_ITEM_ENUM, id_node)
        if not nodes:
            nodes = app.tree_proc(h_tree, app.TREE_ITEM_ENUM, id_node)
            if not nodes:
                return 
        for id_kid, cap in nodes:
            prop    = app.tree_proc(h_tree, app.TREE_ITEM_GET_PROPS, id_kid)
            rng     = app.tree_proc(h_tree, app.TREE_ITEM_GET_RANGE, id_kid)
            subs    = prop['sub_items']
            if rng[0]>=0:
                prop['rng'] = rng
                prop['_t']  = f('{}{}\t{}'
                                , prefix
                                , prop['text']
                                , f('{}:{}', 1+rng[1], 1+rng[3]))
                props.append(prop)
            if subs and more_levels:
                # need items with sub_items too
                tree_items_to_list(props, id_kid, prefix+' '*4, more_levels-1)
        return props
       #def tree_items_to_list
    
    old_api     = app.app_api_version() < '1.0.277'
    w           = get_hist('symbols.w', 600)
    h           = get_hist('symbols.h', 550)
    while True:
        props = tree_items_to_list(more_levels=(levels-1 if levels else 1000))
        if not props:
            ed.cmd(cmds.cmd_TreeUpdate)
            props = tree_items_to_list()
            if not props:
                return app.msg_status(_('No items in Code Tree'))

        items       = [p['_t'] for p in props]
        crt_row     = ed.get_carets()[0][1]
        covers      = [(p['rng'][3]-p['rng'][1], n) for n,p in enumerate(props) 
                        if p['rng'][1] <= crt_row <= p['rng'][3]]
        start_item  = min(covers)[1] if covers else 0
        res = dlg_menu(app.MENU_LIST+app.MENU_NO_FULLFILTER+app.MENU_EDITORFONT
            , w=w, h=h
            , sel=start_item
            , cap=_('Code Tree symbols')
                     + f(' ({})'    , len(items))
                     +(f(' (up {})' , levels    ) if levels else '')
            , its=items 
            + ([_('<Update Code Tree>')] if old_api else [])
            + [_('              <All levels>')]
            + [_('              <Only 1 up level>')]
            + [_('              <Only 2 up levels>')]
            + [_('              <Only 3 up levels>')]
            )
        if res is None: return
        if res==len(props) and old_api:
            ed.cmd(cmds.cmd_TreeUpdate)
            continue#while
        if res==0+len(props) + (1 if old_api else 0):
            levels  = 0
            continue#while
        if res==1+len(props) + (1 if old_api else 0):
            levels  = 1
            continue#while
        if res==2+len(props) + (1 if old_api else 0):
            levels  = 2
            continue#while
        if res==3+len(props) + (1 if old_api else 0):
            levels  = 3
            continue#while
        break
       #while
        
    x, y, x1, y1 = props[res]['rng']
    ed.set_caret(x, y)
    def on_key(self, ed_self, code, state):
        if app.app_api_version()<'1.0.212':     # depr PROC_GET_COMMAND, PROC_GET_COMMAND_PLUGIN
            return app.msg_status(_('Need update CudaText'))
        pass;                  #LOG and log('code, state={}',(code, state))
        if code!=9:                     return True # tab-key=9
        if state:                       return True # SCAM
        pass;                   LOG and log('self.sndt.snp2csgn={}',(self.sndt.snp2csgn))
        if not self.sndt.snp2csgn:      return True # no snips
        if ed_self.get_prop(app.PROP_TAB_COLLECT_MARKERS): return # TAB busy
        
        crts    = ed_self.get_carets()
        if len(crts)>1:                 return True # many carets
        (cCrt, rCrt
        ,cEnd, rEnd)= crts[0]
        if -1!=cEnd or cCrt<2:          return True # with selection

        line    = ed_self.get_text_line(rCrt)
        posC    = line.rfind(SnipData.STARTC, 0, cCrt)
        pass;                   LOG and log('SnipData.STARTC={}',(SnipData.STARTC))
        pass;                   LOG and log('line, posC={}',(line, posC))
        if -1==posC or posC+1==cCrt:    return True # no sign or too near
        rp_snp_pr = line[posC+1:cCrt]
        rpt,snp,prm = SnipData.parse_snip_env(rp_snp_pr)
#       mgRpSnPr= SnipData.reRpSnPr.match(rp_snp_pr).groupdict()
#       rpt     = mgRpSnPr['rp']
#       snp     = mgRpSnPr['sn']
#       prm     = mgRpSnPr['pr']
#       posP    = rp_snp_pr.find(SnipData.PAPAMC)
#       if -1!=posP:
#           snp = line[:posP]
#           prm = line[posP+1:]
        pass;                   LOG and log('rpt,snp,prm={}',(rpt,snp,prm))

        cid     = self.sndt.get_cmdid(snp)
        if not cid:                     return True # no such snip
        pass;                  #LOG and log('cid={}',(cid))

        # Eliminate snp from text
        if not 'Simple way - cut':
            ed_self.delete(   cCrt-len(rp_snp_pr)-1, rCrt, cCrt, rCrt)
            ed_self.set_caret(cCrt-len(rp_snp_pr)-1, rCrt)
        if 'Complex way - undo':
            line_snp= line
            line_pre= line_snp
            line_pur= line_snp[:cCrt-len(rp_snp_pr)-1] + line_snp[cCrt:]
            pass;              #LOG and log('line_pur={}',(line_pur))
            pass;              #LOG and log('line_snp={}',(line_snp))
            good    = False
            undos   = 0
            for iun in range(1+len(rp_snp_pr)):
                ed_self.cmd(cmds.cCommand_Undo)
                undos  += 1
                line_und= ed_self.get_text_line(rCrt)
                pass;          #LOG and log('line_und={}',(line_und))
                if line_pre==line_pur:
                    pass;      #LOG and log('Not hot-snip',())
                    for ird in range(undos):
                        ed_self.cmd(cmds.cCommand_Redo)
                    return True # Not hot-snip
                if line_und==line_pur:
                    pass;      #LOG and log('Good hot-snip',())
                    good    = True
                    break#for iun
                line_pre= line_und
               #for iun
            if not good:
                pass;          #LOG and log('Not good',())
                for ird in range(undos):
                    ed_self.cmd(cmds.cCommand_Redo)
                return True # Not hot-snip

        self._call_cmd(ed_self, cid, rpt, prm)
        return False #block tab-key
Example #31
0
    def _cmt_toggle_line(self, cmt_act, cmt_type='', ed_=ed):
        ''' Add/Remove full line comment
            Params
                cmt_act     'del'   uncomment all lines
                            'add'   comment all lines
                            'bgn'   (un)comment all as toggled first line
                cmt_type    '1st'   at begin of line
                            'bod'   at first not blank
        '''
#       if not apx._check_API('1.0.108'):    return
        lex         = ed_.get_prop(app.PROP_LEXER_CARET)
        prop        = app.lexer_proc(app.LEXER_GET_PROP, lex)
        cmt_sgn     = prop['c_line'] if prop else None
        pass;                  #LOG and log('cmt_type, lex, cmt_sgn={}', (cmt_type, lex, cmt_sgn))
        if not cmt_sgn:
            return app.msg_status(f(_('No line comment for lexer "{}"'), lex))
        # Analize
        bEmpSel     = False
        rWrks       = []
        bUseRepLns  = app.app_api_version()>='1.0.177'
        y1,y2,lines = (-1, -1, []) if bUseRepLns else (None, None, None) # To use API replace_lines
        pass;                  #LOG and log('ed_.get_sel_mode(),app.SEL_NORMAL,app.SEL_COLUMN={}', (ed_.get_sel_mode(),app.SEL_NORMAL,app.SEL_COLUMN))
        crts        = ed_.get_carets()
        if False:pass
        elif ed_.get_sel_mode() == app.SEL_NORMAL:
            bEmpSel     = 1==len(crts) and -1==crts[0][3]
            for (cCrt, rCrt ,cEnd, rEnd) in crts:
                (rCrtMin
                ,rCrtMax)   = apx.minmax(rCrt, rEnd if -1!=rEnd else rCrt)
                if -1!=rEnd and rCrt>rEnd and 0==cCrt:
                    rCrtMax = rCrtMax-1    # For direct section along left bound
                rWrks      += list(range(rCrtMin, rCrtMax+1))
            bUseRepLns  = bUseRepLns and 1==len(crts)
        elif ed_.get_sel_mode() == app.SEL_COLUMN:
            (cBgn
            ,rSelBgn
            ,cEnd
            ,rSelEnd)   = ed_.get_sel_rect()
            rWrks       = list(range(rSelBgn, rSelEnd+1))
        if not rWrks:
            rWrks       = [crts[0][1]]
        pass;                  #LOG and log('rWrks={}', (rWrks))
        y1,y2       = (rWrks[0],rWrks[-1]) if bUseRepLns else (y1,y2)
        pass;                  #LOG and log('y1,y2,lines={}', (y1,y2,lines))
        do_uncmt    = ed_.get_text_line(rWrks[0]).lstrip().startswith(cmt_sgn) \
                        if cmt_act=='bgn' else \
                      True \
                        if cmt_act=='del' else \
                      False
        # Work
        save_bd_col = apx.get_opt('comment_save_column' , False)
        at_min_bd   = apx.get_opt('comment_equal_column', False)
        col_min_bd  = 1000 # infinity
        if at_min_bd:
            for rWrk in rWrks:
                line        = ed_.get_text_line(rWrk)
                pos_body    = line.index(line.lstrip())
                pos_body    = len(line) if 0==len(line.lstrip()) else pos_body
                col_min_bd  = min(pos_body, col_min_bd)
                if 0==col_min_bd:
                    break # for rWrk
        blnks4cmt   = ' '*len(cmt_sgn) # '\t'.expandtabs(len(cmt_sgn))
        pass;                  #LOG and log('rWrks,do_uncmt, save_cols, at_min_bd, col_min_bd={}', (rWrks,do_uncmt,save_bd_col,at_min_bd,col_min_bd))
        for rWrk in rWrks:
            line    = ed_.get_text_line(rWrk)
            pos_body= line.index(line.lstrip())
            pos_body= len(line) if 0==len(line.lstrip()) else pos_body
            pass;              #LOG and log('rWrk,pos_body,line={}', (rWrk,pos_body,line))
            if do_uncmt:
                # Uncomment!
                if not line[pos_body:].startswith(cmt_sgn):
                    # Already no comment
                    if bUseRepLns:
                        lines += [line]
                    continue    #for rWrk
                if False:pass
                elif len(line)==len(cmt_sgn): # and line.startswith(cmt_sgn)
                    line = ''
                elif save_bd_col and (' '==line[0] or
                                      ' '==line[pos_body+len(cmt_sgn)]):
                    # Before or after cmt_sgn must be blank
                    line = line.replace(cmt_sgn, blnks4cmt, 1)
                else:
                    line = line.replace(cmt_sgn, ''       , 1)
            else:
                # Comment!
                if cmt_type=='bod' and line[pos_body:].startswith(cmt_sgn):
                    # Body comment already sets - willnot double it
                    if bUseRepLns:
                        lines += [line]
                    continue    #for rWrk
                if False:pass
                elif cmt_type=='1st' and save_bd_col and line.startswith(blnks4cmt) :
                    line = line.replace(blnks4cmt, cmt_sgn, 1)
               #elif cmt_type=='1st' and save_bd_col #  !line.startswith(blnks4cmt) :
                elif cmt_type=='1st':#  !save_bd_col
                    line = cmt_sgn+line
                elif cmt_type=='bod' and save_bd_col and line.startswith(blnks4cmt):
                    pos_cmnt = col_min_bd if at_min_bd else pos_body
                    pass;          #LOG and log('pos_cmnt={}', (pos_cmnt))
                    if pos_cmnt>=len(cmt_sgn):
                        line = line[:pos_cmnt-len(cmt_sgn)]+cmt_sgn+line[pos_cmnt:             ]
                    else:
                        line = line[:pos_cmnt             ]+cmt_sgn+line[pos_cmnt+len(cmt_sgn):]
                   #line = line[:pos_cmnt-len(cmt_sgn)]+cmt_sgn+line[pos_cmnt:]
                   #line = line[:pos_body-len(cmt_sgn)]+cmt_sgn+line[pos_body:]
               #elif cmt_type=='bod' and save_bd_col #  !line.startswith(blnks4cmt) :
                elif cmt_type=='bod':#  !save_bd_col
                    pos_cmnt = col_min_bd if at_min_bd else pos_body
                    pass;      #LOG and log('pos_cmnt={}', (pos_cmnt))
                    line = line[:pos_cmnt]             +cmt_sgn+line[pos_cmnt:]
                   #line = line[:pos_body]             +cmt_sgn+line[pos_body:]

            pass;              #LOG and log('new line={}', (line))
            if bUseRepLns:
                lines += [line]
            else:
                ed_.set_text_line(rWrk, line)
            #for rWrk
        if bUseRepLns:
            ed_.replace_lines(y1, y2, lines)
        bSkip    = apx.get_opt('comment_move_down', True)
        if bEmpSel and bSkip:
            (cCrt, rCrt, cEnd, rEnd)    = crts[0]
            apx._move_caret_down(cCrt, rCrt)
Example #32
0
    def dlg_config(self):
        ''' Show dlg for change macros list.
        '''
        if app.app_api_version() < FROM_API_VERSION:
            return app.msg_status('Need update CudaText')
        keys_json = app.app_path(app.APP_DIR_SETTINGS) + os.sep + 'keys.json'
        keys = apx._json_loads(
            open(keys_json).read()) if os.path.exists(keys_json) else {}
        GAP = 5

        ids = [mcr['id'] for mcr in self.macros]
        mcr_ind = ids.index(
            self.last_mcr_id) if self.last_mcr_id in ids else -1
        pass
        LOG and log('self.last_mcr_id, mcr_ind={}',
                    (self.last_mcr_id, mcr_ind))
        times = 1
        waits = 5
        chngs = '0'
        endln = '0'
        while True:
            (WD_LST, HT_LST) = (self.dlg_prs.get('w_list', 300),
                                self.dlg_prs.get('h_list', 500))
            (WD_ACTS, HT_ACTS) = (self.dlg_prs.get('w_acts', 300),
                                  self.dlg_prs.get('h_acts', 500))
            (WD_BTN, HT_BTN) = (self.dlg_prs.get('w_btn', 150), 24)
            l_btn = GAP + WD_LST + GAP

            vw_acts = (WD_ACTS > 0)
            WD_ACTS = max(0, WD_ACTS)
            rec_on = ed.get_prop(app.PROP_MACRO_REC)
            lmcrs = len(self.macros)
            pass
            LOG and log('mcr_ind,vw_acts,rec_on={}',
                        (mcr_ind, vw_acts, rec_on))

            nmkys = []
            for mcr in self.macros:
                mcr_cid = 'cuda_macros,run,{}'.format(mcr['id'])
                mcr_keys = keys.get(mcr_cid, {})
                kys = '/'.join([
                    ' * '.join(mcr_keys.get('s1', [])),
                    ' * '.join(mcr_keys.get('s2', []))
                ]).strip('/')
                nmkys += [mcr['nm'] + (' [' + kys + ']' if kys else '')]

            mcr_acts = ''
            if vw_acts and mcr_ind in range(lmcrs):
                mcr = self.macros[mcr_ind]
                mcr_acts = '\t'.join(['# ' + nmkys[mcr_ind]] + mcr['evl'])

            ans = app.dlg_custom(
                'Macros',
                GAP + WD_LST + GAP + WD_BTN + GAP + WD_ACTS + GAP,
                GAP + HT_LST + GAP,
                '\n'.join([] + [
                    C1.join([
                        'type=listbox',
                        POS_FMT(l=GAP, t=GAP, r=GAP + WD_LST, b=GAP + HT_LST),
                        'items=' + '\t'.join(nmkys),
                        'val=' + str(mcr_ind)  # start sel
                        ,
                        'en=' + str(0 if rec_on else 1)  # enabled
                    ]  # i=0
                            )
                ] + ([
                    C1.join([
                        'type=button',
                        POS_FMT(l=l_btn,
                                t=GAP * 1 + HT_BTN * 0,
                                r=l_btn + WD_BTN,
                                b=0),
                        'cap=&View actions...',
                        'props=' +
                        str(0 if rec_on or 0 == lmcrs else 1)  # default
                        ,
                        'en=' +
                        str(0 if rec_on or 0 == lmcrs else 1)  # enabled
                    ]  # i=1
                            )
                ] if vw_acts else []) + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=l_btn,
                                t=GAP * 2 + HT_BTN * 1,
                                r=l_btn + WD_BTN,
                                b=0),
                        'cap=Hot&keys...',
                        'en=' +
                        str(0 if rec_on or 0 == lmcrs else 1)  # enabled
                    ]  # i=2 if vw_acts else i=1
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=l_btn,
                                t=GAP * 3 + HT_BTN * 2,
                                r=l_btn + WD_BTN,
                                b=0),
                        'cap=Re&name...',
                        'en=' +
                        str(0 if rec_on or 0 == lmcrs else 1)  # enabled
                    ]  # i=3 if vw_acts else i=2
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=l_btn,
                                t=GAP * 4 + HT_BTN * 3,
                                r=l_btn + WD_BTN,
                                b=0),
                        'cap=&Delete...',
                        'en=' +
                        str(0 if rec_on or 0 == lmcrs else 1)  # enabled
                    ]  # i=4 if vw_acts else i=3
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=l_btn,
                                t=GAP * 6 + HT_BTN * 5,
                                r=l_btn + WD_BTN,
                                b=0),
                        'cap=&Run!',
                        'props=' +
                        str(1 if not vw_acts and not rec_on else 0)  # default
                        ,
                        'en=' +
                        str(0 if rec_on or 0 == lmcrs else 1)  # enabled
                    ]  # i=5 if vw_acts else i=4
                            )
                ] + [
                    C1.join([
                        'type=label',
                        POS_FMT(l=l_btn,
                                t=GAP * 7 + HT_BTN * 6 + 3,
                                r=l_btn + int(WD_BTN / 3),
                                b=0), 'cap=&Times'
                    ]  # i=6 if vw_acts else i=5
                            )
                ] + [
                    C1.join([
                        'type=spinedit',
                        POS_FMT(l=l_btn + int(WD_BTN / 3) + GAP,
                                t=GAP * 7 + HT_BTN * 6,
                                r=l_btn + WD_BTN,
                                b=0),
                        'val=' + str(times),
                        'props=0,{},1'.format(self.dlg_prs.get('times', 1000)),
                        'en=' + str(0 if rec_on else 1)  # enabled
                    ]  # i=7 if vw_acts else i=6
                            )
                ] + [
                    C1.join([
                        'type=label',
                        POS_FMT(l=l_btn,
                                t=GAP * 8 + HT_BTN * 7 + 3,
                                r=l_btn + int(WD_BTN / 3),
                                b=0), 'cap=&Wait'
                    ]  # i=8 if vw_acts else i=7
                            )
                ] + [
                    C1.join([
                        'type=spinedit',
                        POS_FMT(l=l_btn + int(WD_BTN / 3) + GAP,
                                t=GAP * 8 + HT_BTN * 7,
                                r=l_btn + WD_BTN - 40,
                                b=0),
                        'val=' + str(waits),
                        'props=1,3600,1',
                        'en=' + str(0 if rec_on else 1)  # enabled
                    ]  # i=9 if vw_acts else i=8
                            )
                ] + [
                    C1.join([
                        'type=label',
                        POS_FMT(l=l_btn + WD_BTN - 40 + GAP,
                                t=GAP * 8 + HT_BTN * 7 + 3,
                                r=l_btn + WD_BTN,
                                b=0), 'cap=sec'
                    ]  # i=10 if vw_acts else i=9
                            )
                ] + [
                    C1.join([
                        'type=check',
                        POS_FMT(l=l_btn,
                                t=GAP * 9 + HT_BTN * 8,
                                r=l_btn + WD_BTN,
                                b=0), 'cap=While text c&hanges', 'val=' + chngs
                    ]  # i=11 if vw_acts else i=10
                            )
                ] + [
                    C1.join([
                        'type=check',
                        POS_FMT(l=l_btn,
                                t=GAP * 10 + HT_BTN * 9,
                                r=l_btn + WD_BTN,
                                b=0), 'cap=Until c&aret on last line', 'val=' +
                        endln
                    ]  # i=12 if vw_acts else i=11
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=l_btn,
                                t=GAP * 12 + HT_BTN * 11,
                                r=l_btn + WD_BTN,
                                b=0),
                        'cap={}'.format(
                            '&Stop record' if rec_on else '&Start record'),
                        'props=' +
                        str(1 if rec_on or 0 == lmcrs else 0)  # default
                    ]  # i=13 if vw_acts else i=12
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=l_btn,
                                t=GAP * 13 + HT_BTN * 12,
                                r=l_btn + WD_BTN,
                                b=0),
                        'cap=Canc&el record',
                        'en=' + str(1 if rec_on else 0)  # enabled
                    ]  # i=14 if vw_acts else i=13
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=l_btn,
                                t=HT_LST - HT_BTN * 2,
                                r=l_btn + WD_BTN,
                                b=0),
                        'cap=C&ustom...',
                        'en=' + str(0 if rec_on else 1)  # enabled
                    ]  # i=15 if vw_acts else i=14
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=l_btn,
                                t=GAP + HT_LST - HT_BTN * 1,
                                r=l_btn + WD_BTN,
                                b=0), 'cap=&Close'
                    ]  # i=16 if vw_acts else i=15
                            )
                ] + ([
                    C1.join([
                        'type=memo',
                        POS_FMT(l=GAP + WD_LST + GAP + WD_BTN + GAP,
                                t=GAP,
                                r=GAP + WD_LST + GAP + WD_BTN + GAP + WD_ACTS,
                                b=GAP + HT_ACTS),
                        'val=' + mcr_acts,
                        'props=1,1,1'  # ro,mono,border
                    ]  # i=17
                            )
                ] if vw_acts else [])),
                apx.icase(
                    vw_acts and not rec_on,
                    0  # View
                    ,
                    not vw_acts and not rec_on,
                    0  # View
                    ,
                    vw_acts and rec_on,
                    11,
                    not vw_acts and rec_on,
                    10))  # start focus
            pass
            LOG and log('ans={}', ans)
            if ans is None: break  #while
            (ans_i, vals) = ans
            ans_s = apx.icase(
                False, '', vw_acts and ans_i == 1, 'view', vw_acts
                and ans_i == 2, 'hotkeys', not vw_acts and ans_i == 1,
                'hotkeys', vw_acts and ans_i == 3, 'rename', not vw_acts
                and ans_i == 2, 'rename', vw_acts and ans_i == 4, 'delete',
                not vw_acts and ans_i == 3, 'delete', vw_acts and ans_i == 5,
                'run', not vw_acts and ans_i == 4, 'run', vw_acts
                and ans_i == 12, 'rec', not vw_acts and ans_i == 7, 'rec',
                vw_acts and ans_i == 14, 'cancel', not vw_acts and ans_i == 13,
                'cancel', vw_acts and ans_i == 15, 'custom', not vw_acts
                and ans_i == 14, 'custom', vw_acts and ans_i == 16, 'close',
                not vw_acts and ans_i == 15, 'close', '?')
            mcr_ind = int(vals.splitlines()[0])
            times = int(vals.splitlines()[7 if vw_acts else 6])
            waits = int(vals.splitlines()[9 if vw_acts else 8])
            chngs = vals.splitlines()[11 if vw_acts else 10]
            endln = vals.splitlines()[12 if vw_acts else 11]
            pass
            LOG and log('mcr_ind,times,waits,chngs,endln={}',
                        (mcr_ind, times, waits, chngs, endln))

            if 0 != lmcrs and mcr_ind in range(lmcrs):
                mcr = self.macros[mcr_ind]
                self.last_mcr_id = mcr['id']

            if ans_s == 'close': break  #while
            if ans_s == 'custom':  #Custom
                custs = app.dlg_input_ex(
                    5, 'Custom dialog Macros',
                    'Height of macro list (min 450)',
                    str(self.dlg_prs.get('h_list', 400)),
                    'Width of macro list (min 200)',
                    str(self.dlg_prs.get('w_list', 500)),
                    'Width of action list (min 200, <=0-hide)',
                    str(self.dlg_prs.get('w_acts',
                                         500)), 'Width of buttons (min 150)',
                    str(self.dlg_prs.get('w_btn',
                                         150)), 'Max run times (min 100)',
                    str(self.dlg_prs.get('times', 1000)))
                if custs is not None:
                    self.dlg_prs['h_list'] = max(450, int(custs[0]))
                    self.dlg_prs['h_acts'] = self.dlg_prs['h_list']
                    self.dlg_prs['w_list'] = max(200, int(custs[1]))
                    self.dlg_prs['w_acts'] = max(200, int(
                        custs[2])) if int(custs[2]) > 0 else int(custs[2])
                    self.dlg_prs['w_btn'] = max(150, int(custs[3]))
                    self.dlg_prs['times'] = max(100, int(custs[4]))
                    open(MACROS_JSON, 'w').write(
                        json.dumps(
                            {
                                'ver': JSON_FORMAT_VER,
                                'list': self.macros,
                                'dlg_prs': self.dlg_prs
                            },
                            indent=4))
                continue  #while

            if mcr_ind not in range(lmcrs):
                app.msg_box('Select macro', app.MB_OK)
                continue  #while

            what = ''
            changed = False
            if False: pass

            elif ans_s == 'view':  #View
                continue  #while

            elif ans_s == 'rename':  #Rename
                mcr_nm = app.dlg_input(
                    'New name for: {}'.format(nmkys[mcr_ind]), mcr['nm'])
                if mcr_nm is None or mcr_nm == mcr['nm']: continue  #while
                while mcr_nm in [mcr['nm'] for mcr in self.macros]:
                    app.msg_box(
                        'Select other name.\nMacro names now are:\n\n' +
                        '\n'.join(nmkys), app.MB_OK)
                    mcr_nm = app.dlg_input(
                        'New name for: {}'.format(nmkys[mcr_ind]), mcr_nm)
                    if mcr_nm is None or mcr_nm == mcr['nm']:
                        break  #while mcr_nm
                if mcr_nm is None or mcr_nm == mcr['nm']: continue  #while
                what = 'rename'
                mcr['nm'] = mcr_nm
                changed = True

            elif ans_s == 'delete':  #Del
                if app.msg_box('Delete macro\n    {}'.format(nmkys[mcr_ind]),
                               app.MB_YESNO) != app.ID_YES:
                    continue  #while
                what = 'delete:' + str(mcr['id'])
                del self.macros[mcr_ind]
                mcr_ind = min(mcr_ind, len(self.macros) - 1)
                changed = True

            elif ans_s == 'hotkeys':  #Hotkeys
                app.dlg_hotkeys('cuda_macros,run,' + str(mcr['id']))
                keys = apx._json_loads(open(
                    keys_json).read()) if os.path.exists(keys_json) else {}
                changed = True

            elif ans_s == 'run':  #Run
                if (times == 0 and waits == 0 and chngs == '0'
                        and endln == '0'):
                    app.msg_box('Select stop condition', app.MB_OK)
                    continue
                self.run(mcr['id'], max(0, times), max(0, waits), chngs == '1',
                         endln == '1')
                return

            elif ans_s == 'rec' and not rec_on:  #Start record
                return ed.cmd(cmds.cmd_MacroStart)
            elif ans_s == 'rec' and rec_on:  #Stop record
                self.need_dlg = True
                return ed.cmd(
                    cmds.cmd_MacroStop
                )  # Return for clear rec-mode in StatusBar, will recall from on_macro
            elif ans_s == 'cancel' and rec_on:  #Cancel record
                return ed.cmd(cmds.cmd_MacroCancel
                              )  # Return for clear rec-mode in StatusBar

            if changed:
                self._do_acts(what)
Example #33
0
    def dlg(self):
        if app.app_api_version()<'1.0.146':  return app.msg_status(_("Need update CudaText"))   # dlg_custom: "type=tabs"
        pass;                  #LOG and log('=',())
        fvdata  = get_fav_data()
        tab_nms = fvdata.get('fv_tabs', [_('Fi&les'), _('Pro&jects')])
        tabs    = fvdata.get('fv_tab', 0)
        files   = fvdata.get('fv_files', [])
        projs   = fvdata.get('fv_projs', [])
        fold    = fvdata.get('fv_fold', True)
        last    = fvdata.get('fv_last', 0)
        fvrs_h  = _('Choose file to open.')
        brow_h  = _('Choose file to append.'
                '\r    Shift+Click to choose folder'
                   )
        def n2c(n):
            if  1<=n<=10:                   return str(n%10)
            if 11<=n<=11+ord('Z')-ord('A'): return chr(n-11+ord('A'))
            return ' '
        while True:
            paths   = files if tabs==0 else projs
            last    = min(max(0, last), len(paths)-1)
            hasf    = bool(paths)
            itms    = [f('{}: {}{}'
                    , n2c(1+nf)
                    , os.path.basename(fn) 
                        if os.path.isfile(fn) else 
                      '['+os.path.basename(fn)+']' 
                        if os.path.isdir(fn) else 
                      '? '+os.path.basename(fn) 
                    , ' ('+os.path.dirname(fn)+')' if fold else ''
                    ) 
                    for nf,fn in enumerate(paths)]
            itms    = itms if itms else [' ']
            aid,vals,chds   = dlg_wrapper(_('Favorites'), 500+10,300+10,
                 [
#                 dict(           tp='lb'   ,t=5            ,l=5            ,w=400      ,cap=_('&Files:')   ,hint=fvrs_h        ) # &f
                  dict(cid='tabs',tp='tabs' ,t=5,h=30       ,l=5            ,w=400-3    ,items=tab_nms          ,act='1'        ) # 
                 ,dict(cid='fvrs',tp='lbx'  ,t=5+23,h=240   ,l=5            ,w=400-5    ,items=itms                     ,en=hasf)
                 ,dict(cid='open',tp='bt'   ,t=5+20         ,l=5+400        ,w=100      ,cap=_('&Open')     ,props='1'  ,en=hasf) #     default
                 ,dict(cid='addc',tp='bt'   ,t=5+65         ,l=5+400        ,w=100      ,cap=_('&Add opened')           ,en=(tabs==0)) # &a
                 ,dict(cid='brow',tp='bt'   ,t=5+90         ,l=5+400        ,w=100      ,cap=_('Add&...')   ,hint=brow_h        ) # &.
                 ,dict(cid='delt',tp='bt'   ,t=5+135        ,l=5+400        ,w=100      ,cap=_('&Delete')               ,en=hasf) # &d
                 ,dict(cid='fvup',tp='bt'   ,t=5+180        ,l=5+400        ,w=100      ,cap=_('Move &up')              ,en=hasf) # &u
                 ,dict(cid='fvdn',tp='bt'   ,t=5+205        ,l=5+400        ,w=100      ,cap=_('Move do&wn')            ,en=hasf) # &w
                 ,dict(cid='fold',tp='ch'   ,tid='-'        ,l=5            ,w=120      ,cap=_('Show &paths')   ,act='1'        ) # &p
                 ,dict(cid='help',tp='bt'   ,t=5+300-53     ,l=5+500-100    ,w=100      ,cap=_('&Help')                         ) # &h
                 ,dict(cid='-'   ,tp='bt'   ,t=5+300-28     ,l=5+500-100    ,w=100      ,cap=_('Close')                         )
                 ]+
                 [dict(cid='act'+str(n),tp='bt',cap='&'+str((n+1)%10),t=0,l=0,w=0) for n in range(10)]                           # &1 - &0
                 ,    dict(fvrs=last
                          ,tabs=tabs
                          ,fold=fold), focus_cid='fvrs')
            if aid is None or aid=='-': return None
            scam    = app.app_proc(app.PROC_GET_KEYSTATE, '')
            if aid=='help':
                dlg_wrapper(_('Help for "Favorites"'), 410, 310,
                     [dict(cid='htxt',tp='me'    ,t=5  ,h=300-28,l=5          ,w=400  ,props='1,0,1'  ) #  ro,mono,border
                     ,dict(cid='-'   ,tp='bt'    ,t=5+300-23    ,l=5+400-80   ,w=80   ,cap=_('&Close'))
                     ], dict(htxt=_(  '• Quick opening.'
                                    '\rUse Alt+1, Alt+2, ..., Alt+9, Alt+0'
                                    '\rto direct open file'
                                    '\r"1: *", "2: *",..., "9: *", "0: *"'
                                    '\r '
                                    '\r• Import. '
                                    '\rSelect "SynFav.ini" for "Add..." to import Favorites from SynWrite.'
                                    '\rSee "SynFav.ini" in folder "SynWrite/Settings".'
                                    )
                     ), focus_cid='htxt')
                continue#while
            
            fold    = vals['fold']
            last    = vals['fvrs']
            tabs    = vals['tabs']
            def save_and_open(path):
                fvdata['fv_tab']    = tabs
                fvdata['fv_files']  = files
                fvdata['fv_projs']  = projs
                fvdata['fv_fold' ]  = fold 
                fvdata['fv_last' ]  = last 
                save_fav_data(fvdata)
                if os.path.isdir( path):
                    path= app.dlg_file(True, '', path, '')
                    if not path:    return False
                app.file_open(path)
                return True
               #def save_and_open
            if aid=='open' and paths and last>=0:
                if save_and_open(paths[last]):
                    break#while
            if aid[0:3]=='act' and paths:
                nf  = int(aid[3])
                if nf<len(paths) and save_and_open(paths[nf]):
                    break#while
                    
            if aid=='tabs':
                pass;          #LOG and log('tabs={}',(tabs))
                continue#while
            
            # Modify
            store_b = 'fold' in chds
            if False:pass
            elif aid=='addc':
                fn      = ed.get_filename()
                if fn and not any([os.path.samefile(fn, f) for f in paths]):
                    paths  += [fn]
                    store_b = True
#           elif aid=='brow' and scam=='s': 
#               # Ask dir
#               dr      = dlg_dir('')
#               if dr
            elif aid=='brow':
                # Ask file
                fn      = app.dlg_dir('') if scam=='s' else app.dlg_file(True, '', '', '')
                if fn and os.path.basename(fn).upper()=='SynFav.ini'.upper():
                    store_b = import_SynFav(fn, paths)
                elif fn and not any([os.path.samefile(fn, f) for f in paths]):
                    paths  += [fn]
                    store_b = True
            elif aid=='delt' and paths and last>=0:
                del paths[last]
                last    = min(max(0, last), len(paths)-1)
                store_b = True
            elif aid in ('fvup', 'fvdn') and paths:
                newp    = last + (-1 if aid=='fvup' else +1)
                if 0<=newp<len(paths):
                    paths[last], paths[newp] = paths[newp], paths[last]
                    last    = newp
                    store_b = True
            
            # Store
            if store_b:
                fvdata['fv_tab']    = tabs
                fvdata['fv_files']  = files
                fvdata['fv_projs']  = projs
                fvdata['fv_fold' ]  = fold 
                fvdata['fv_last' ]  = last 
                save_fav_data(fvdata)
Example #34
0
    def dlg_config(self):
        ''' Show dlg for change macros list.
        '''
        if app.app_api_version()<FROM_API_VERSION:  return app.msg_status('Need update CudaText')
        keys_json   = app.app_path(app.APP_DIR_SETTINGS)+os.sep+'keys.json'
        keys        = apx._json_loads(open(keys_json).read()) if os.path.exists(keys_json) else {}
        GAP     = 5
        
        ids     = [mcr['id'] for mcr in self.macros]
        mcr_ind = ids.index(self.last_mcr_id) if self.last_mcr_id in ids else -1
        pass;                   LOG and log('self.last_mcr_id, mcr_ind={}',(self.last_mcr_id,mcr_ind))
        times   = 1
        waits   = 5
        chngs   = '0'
        endln   = '0'
        while True:
            (WD_LST
            ,HT_LST)= (self.dlg_prs.get('w_list', 300)
                      ,self.dlg_prs.get('h_list', 500))
            (WD_ACTS
            ,HT_ACTS)=(self.dlg_prs.get('w_acts', 300)
                      ,self.dlg_prs.get('h_acts', 500))
            (WD_BTN
            ,HT_BTN)= (self.dlg_prs.get('w_btn', 150), 24)
            l_btn   = GAP+WD_LST+GAP
            
            vw_acts = (WD_ACTS>0)
            WD_ACTS = max(0, WD_ACTS)
            rec_on  = ed.get_prop(app.PROP_MACRO_REC)
            lmcrs   = len(self.macros)
            pass;               LOG and log('mcr_ind,vw_acts,rec_on={}',(mcr_ind,vw_acts,rec_on))

            nmkys   = []
            for mcr in self.macros:
                mcr_cid = 'cuda_macros,run,{}'.format(mcr['id'])
                mcr_keys= keys.get(mcr_cid, {})
                kys     = '/'.join([' * '.join(mcr_keys.get('s1', []))
                                   ,' * '.join(mcr_keys.get('s2', []))
                                   ]).strip('/')
                nmkys  += [mcr['nm'] + (' ['+kys+']' if kys else '')]

            mcr_acts= ''
            if vw_acts and mcr_ind in range(lmcrs):
                mcr     = self.macros[mcr_ind]
                mcr_acts= '\t'.join(['# '+nmkys[mcr_ind]] + mcr['evl'])

            ans = app.dlg_custom('Macros'   ,GAP+WD_LST+GAP+WD_BTN+GAP+WD_ACTS+GAP,GAP+HT_LST+GAP, '\n'.join([]
            +[C1.join(['type=listbox'   ,POS_FMT(l=GAP,    t=GAP,           r=GAP+WD_LST,   b=GAP+HT_LST)
                      ,'items=' +'\t'.join(nmkys)
                      ,'val='   +str(mcr_ind)  # start sel
                      ,'en='    +str(0 if rec_on else 1)        # enabled
                      ] # i=0
             )]
            +([C1.join(['type=button'    ,POS_FMT(l=l_btn,  t=GAP*1+HT_BTN*0,    r=l_btn+WD_BTN, b=0)
                      ,'cap=&View actions...'
                      ,'props=' +str(0 if    rec_on or 0==lmcrs else 1)    # default
                      ,'en='    +str(0 if    rec_on or 0==lmcrs else 1)    # enabled
                      ] # i=1
             )] if vw_acts else [])
            +[C1.join(['type=button'    ,POS_FMT(l=l_btn,  t=GAP*2+HT_BTN*1,    r=l_btn+WD_BTN, b=0)
                      ,'cap=Hot&keys...'
                      ,'en='    +str(0 if    rec_on or 0==lmcrs else 1)     # enabled
                      ] # i=2 if vw_acts else i=1
             )]
            +[C1.join(['type=button'    ,POS_FMT(l=l_btn,  t=GAP*3+HT_BTN*2,    r=l_btn+WD_BTN, b=0)
                      ,'cap=Re&name...'
                      ,'en='    +str(0 if    rec_on or 0==lmcrs else 1)     # enabled
                      ] # i=3 if vw_acts else i=2
             )]
            +[C1.join(['type=button'    ,POS_FMT(l=l_btn,  t=GAP*4+HT_BTN*3,    r=l_btn+WD_BTN, b=0)
                      ,'cap=&Delete...'
                      ,'en='    +str(0 if    rec_on or 0==lmcrs else 1)     # enabled
                      ] # i=4 if vw_acts else i=3
             )]

            +[C1.join(['type=button'    ,POS_FMT(l=l_btn,                   t=GAP*6+HT_BTN*5,    r=l_btn+WD_BTN, b=0)
                      ,'cap=&Run!'
                      ,'props=' +str(1 if not vw_acts and not rec_on else 0)     # default
                      ,'en='    +str(0 if    rec_on or 0==lmcrs else 1)     # enabled
                      ] # i=5 if vw_acts else i=4
             )]
            +[C1.join(['type=label'     ,POS_FMT(l=l_btn,                   t=GAP*7+HT_BTN*6+3, r=l_btn+int(WD_BTN/3),b=0)
                      ,'cap=&Times'
                      ] # i=6 if vw_acts else i=5
             )]
            +[C1.join(['type=spinedit'  ,POS_FMT(l=l_btn+int(WD_BTN/3)+GAP, t=GAP*7+HT_BTN*6,   r=l_btn+WD_BTN, b=0)
                      ,'val='   +str(times)
                      ,'props=0,{},1'.format(self.dlg_prs.get('times',  1000))
                      ,'en='    +str(0 if    rec_on else 1)     # enabled
                      ] # i=7 if vw_acts else i=6
             )]
            +[C1.join(['type=label'     ,POS_FMT(l=l_btn,                   t=GAP*8+HT_BTN*7+3, r=l_btn+int(WD_BTN/3),b=0)
                      ,'cap=&Wait'
                      ] # i=8 if vw_acts else i=7
             )]
            +[C1.join(['type=spinedit'  ,POS_FMT(l=l_btn+int(WD_BTN/3)+GAP, t=GAP*8+HT_BTN*7,   r=l_btn+WD_BTN-40, b=0)
                      ,'val='   +str(waits)
                      ,'props=1,3600,1'
                      ,'en='    +str(0 if    rec_on else 1)     # enabled
                      ] # i=9 if vw_acts else i=8
             )]
            +[C1.join(['type=label'     ,POS_FMT(l=l_btn+WD_BTN-40+GAP,     t=GAP*8+HT_BTN*7+3, r=l_btn+WD_BTN,b=0)
                      ,'cap=sec'
                      ] # i=10 if vw_acts else i=9
             )]
            +[C1.join(['type=check'     ,POS_FMT(l=l_btn,                   t=GAP*9+HT_BTN*8, r=l_btn+WD_BTN,b=0)
                      ,'cap=While text c&hanges'
                      ,'val='   +chngs
                      ] # i=11 if vw_acts else i=10
             )]
            +[C1.join(['type=check'     ,POS_FMT(l=l_btn,                   t=GAP*10+HT_BTN*9, r=l_btn+WD_BTN,b=0)
                      ,'cap=Until c&aret on last line'
                      ,'val='   +endln
                      ] # i=12 if vw_acts else i=11
             )]

            +[C1.join(['type=button'    ,POS_FMT(l=l_btn,  t=GAP*12+HT_BTN*11,    r=l_btn+WD_BTN, b=0)
                      ,'cap={}'.format('&Stop record' if rec_on else '&Start record')
                      ,'props=' +str(1 if    rec_on or 0==lmcrs else 0)     # default
                      ] # i=13 if vw_acts else i=12
             )]
            +[C1.join(['type=button'    ,POS_FMT(l=l_btn,  t=GAP*13+HT_BTN*12,    r=l_btn+WD_BTN, b=0)
                      ,'cap=Canc&el record'
                      ,'en='    +str(1 if    rec_on else 0)     # enabled
                      ] # i=14 if vw_acts else i=13
             )]

            +[C1.join(['type=button'    ,POS_FMT(l=l_btn,  t=    HT_LST-HT_BTN*2, r=l_btn+WD_BTN, b=0)
                      ,'cap=C&ustom...'
                      ,'en='    +str(0 if    rec_on else 1)     # enabled
                      ] # i=15 if vw_acts else i=14
             )]
            +[C1.join(['type=button'    ,POS_FMT(l=l_btn,  t=GAP+HT_LST-HT_BTN*1, r=l_btn+WD_BTN, b=0)
                      ,'cap=&Close'
                      ] # i=16 if vw_acts else i=15
             )]
            +([C1.join(['type=memo'      ,POS_FMT(l=GAP+WD_LST+GAP+WD_BTN+GAP,   t=GAP,  r=GAP+WD_LST+GAP+WD_BTN+GAP+WD_ACTS, b=GAP+HT_ACTS)
                      ,'val='+mcr_acts
                      ,'props=1,1,1'    # ro,mono,border
                      ] # i=17
             )] if vw_acts else [])
            ), apx.icase(    vw_acts and not rec_on, 0  # View
                        ,not vw_acts and not rec_on, 0  # View
                        ,    vw_acts and     rec_on, 11
                        ,not vw_acts and     rec_on, 10
                        ))    # start focus
            pass;               LOG and log('ans={}',ans)
            if ans is None:  break #while
            (ans_i
            ,vals)  = ans
            ans_s   = apx.icase(False,''
                       ,vw_acts and ans_i==1, 'view'
                       ,vw_acts and ans_i==2, 'hotkeys' ,not vw_acts and ans_i==1, 'hotkeys'
                       ,vw_acts and ans_i==3, 'rename'  ,not vw_acts and ans_i==2, 'rename' 
                       ,vw_acts and ans_i==4, 'delete'  ,not vw_acts and ans_i==3, 'delete' 
                       ,vw_acts and ans_i==5, 'run'     ,not vw_acts and ans_i==4, 'run'    
                       ,vw_acts and ans_i==12,'rec'     ,not vw_acts and ans_i==7, 'rec'    
                       ,vw_acts and ans_i==14,'cancel'  ,not vw_acts and ans_i==13,'cancel' 
                       ,vw_acts and ans_i==15,'custom'  ,not vw_acts and ans_i==14,'custom' 
                       ,vw_acts and ans_i==16,'close'   ,not vw_acts and ans_i==15,'close'  
                       ,'?')
            mcr_ind = int(vals.splitlines()[0])
            times   = int(vals.splitlines()[ 7 if vw_acts else  6])
            waits   = int(vals.splitlines()[ 9 if vw_acts else  8])
            chngs   =     vals.splitlines()[11 if vw_acts else 10]
            endln   =     vals.splitlines()[12 if vw_acts else 11]
            pass;               LOG and log('mcr_ind,times,waits,chngs,endln={}',(mcr_ind,times,waits,chngs,endln))

            if 0!=lmcrs and mcr_ind in range(lmcrs):
                mcr     = self.macros[mcr_ind]
                self.last_mcr_id = mcr['id']
            
            if ans_s=='close':  break #while
            if ans_s=='custom': #Custom
                custs   = app.dlg_input_ex(5, 'Custom dialog Macros'
                    , 'Height of macro list (min 450)'          , str(self.dlg_prs.get('h_list', 400))
                    , 'Width of macro list (min 200)'           , str(self.dlg_prs.get('w_list', 500))
                    , 'Width of action list (min 200, <=0-hide)', str(self.dlg_prs.get('w_acts', 500))
                    , 'Width of buttons (min 150)'              , str(self.dlg_prs.get('w_btn',  150))
                    , 'Max run times (min 100)'                 , str(self.dlg_prs.get('times',  1000))
                    )
                if custs is not None:
                    self.dlg_prs['h_list']  = max(450, int(custs[0]));  self.dlg_prs['h_acts'] = self.dlg_prs['h_list']
                    self.dlg_prs['w_list']  = max(200, int(custs[1]))
                    self.dlg_prs['w_acts']  = max(200, int(custs[2])) if int(custs[2])>0 else int(custs[2])
                    self.dlg_prs['w_btn']   = max(150, int(custs[3]))
                    self.dlg_prs['times']   = max(100, int(custs[4]))
                    open(MACROS_JSON, 'w').write(json.dumps({'ver':JSON_FORMAT_VER, 'list':self.macros, 'dlg_prs':self.dlg_prs}, indent=4))
                continue #while
            
            if mcr_ind not in range(lmcrs):
                app.msg_box('Select macro', app.MB_OK)
                continue #while
            
            what    = ''
            changed = False
            if False:pass
                
            elif ans_s=='view': #View
                continue #while

            elif ans_s=='rename': #Rename
                mcr_nm      = app.dlg_input('New name for: {}'.format(nmkys[mcr_ind])
                                           ,mcr['nm'])
                if mcr_nm is None or mcr_nm==mcr['nm']:     continue #while
                while mcr_nm in [mcr['nm'] for mcr in self.macros]:
                    app.msg_box('Select other name.\nMacro names now are:\n\n'+'\n'.join(nmkys), app.MB_OK)
                    mcr_nm  = app.dlg_input('New name for: {}'.format(nmkys[mcr_ind])
                                           ,mcr_nm)
                    if mcr_nm is None or mcr_nm==mcr['nm']: break #while mcr_nm
                if mcr_nm is None or mcr_nm==mcr['nm']:     continue #while
                what        = 'rename'
                mcr['nm']   = mcr_nm
                changed = True
                
            elif ans_s=='delete': #Del
                if app.msg_box( 'Delete macro\n    {}'.format(nmkys[mcr_ind])
                              , app.MB_YESNO)!=app.ID_YES:  continue #while
                what    = 'delete:'+str(mcr['id'])
                del self.macros[mcr_ind]
                mcr_ind = min(mcr_ind, len(self.macros)-1)
                changed = True
                
            elif ans_s=='hotkeys': #Hotkeys
                app.dlg_hotkeys('cuda_macros,run,'+str(mcr['id']))
                keys    = apx._json_loads(open(keys_json).read()) if os.path.exists(keys_json) else {}
                changed = True

            elif ans_s=='run': #Run
                if (times==0 
                and waits==0
                and chngs=='0'
                and endln=='0'):
                    app.msg_box('Select stop condition', app.MB_OK)
                    continue
                self.run(mcr['id'], max(0, times), max(0, waits), chngs=='1', endln=='1')
                return

            elif ans_s=='rec'    and not rec_on: #Start record
                return ed.cmd(cmds.cmd_MacroStart)
            elif ans_s=='rec'    and     rec_on: #Stop record
                self.need_dlg = True
                return ed.cmd(cmds.cmd_MacroStop)       # Return for clear rec-mode in StatusBar, will recall from on_macro
            elif ans_s=='cancel' and     rec_on: #Cancel record
                return ed.cmd(cmds.cmd_MacroCancel)     # Return for clear rec-mode in StatusBar
                
            if changed:
                self._do_acts(what)
Example #35
0
 def dlg_import(self):
     ''' Show dlg for import some macros.
     '''
     if app.app_api_version()<FROM_API_VERSION:  return app.msg_status('Need update CudaText')
     (imp_file
     ,mcrs)  = self.dlg_import_choose_mcrs()
     if imp_file is None:    return
     lmcrs   = len(mcrs)
     
     GAP     = 5
     (WD_LST
     ,HT_LST)= (500
               ,500)
     crt,sels= '0', ['1'] * lmcrs
     while True:
         ans = app.dlg_custom('Import macros'   ,GAP+WD_LST+GAP, GAP*5+HT_LST+25*2, '\n'.join([]
         +[C1.join(['type=label'         ,POS_FMT(l=GAP,             t=GAP+3,            r=GAP+85,     b=0)
                   ,'cap=Import &from'
                   ] # i=0
          )]
         +[C1.join(['type=edit'         ,POS_FMT(l=GAP+85,           t=GAP,              r=GAP+WD_LST-35,b=0)
                   ,'val={}'.format(imp_file)
                   ] # i=1
          )]
         +[C1.join(['type=button'        ,POS_FMT(l=GAP+HT_LST-35,   t=GAP-2,            r=GAP+WD_LST,   b=0)
                   ,'cap=&...'
                   ] # i=2
          )]
         +[C1.join(['type=checklistbox' ,POS_FMT(l=GAP,             t=GAP*2+30,          r=GAP+WD_LST,   b=GAP+25+HT_LST)
                   ,'items=' +'\t'.join([mcr['nm'] for mcr in mcrs])
                   ,'val='   + crt+';'+','.join(sels)
                   ] # i=3
          )]
         +[C1.join(['type=button'        ,POS_FMT(l=GAP*1,           t=GAP*3+25+HT_LST,  r=GAP*1+80*1,   b=0)
                   ,'cap=Check &all'
                   ] # i=4
          )]
         +[C1.join(['type=button'        ,POS_FMT(l=GAP*2+80,        t=GAP*3+25+HT_LST,  r=GAP*2+80*2,   b=0)
                   ,'cap=U&ncheck all'
                   ] # i=5
          )]
         +[C1.join(['type=button'        ,POS_FMT(l=    WD_LST-60*2, t=GAP*3+25+HT_LST,  r=    WD_LST-60*1,   b=0)
                   ,'cap=&Import'
                   ] # i=6
          )]
         +[C1.join(['type=button'        ,POS_FMT(l=GAP+WD_LST-60*1, t=GAP*3+25+HT_LST,  r=GAP+WD_LST-60*0,   b=0)
                   ,'cap=&Close'
                   ] # i=7
          )]
         ), 3)    # start focus
         pass;               LOG and log('ans={}',ans)
         if ans is None:  break #while
         (ans_i
         ,vals)  = ans
         ans_s   = apx.icase(False,''
                    ,ans_i==2, 'file'
                    ,ans_i==4, 'all'
                    ,ans_i==5, 'no'
                    ,ans_i==6, 'imp'
                    ,ans_i==7, 'close'
                    )
         if ans_s=='close':  break #while
         v_3     = vals.splitlines()[3]
         crt,sels= v_3.split(';')
         sels    = sels.strip(',').split(',')
         pass;               LOG and log('sels={}',sels)
         if False:pass
         elif ans_s=='file':
             (new_imp_file
             ,new_mcrs)  = self.dlg_import_choose_mcrs()
             if new_imp_file is None:    continue #while
             imp_file    = new_imp_file
             mcrs        = new_mcrs
             lmcrs       = len(mcrs)
             crt,sels    = '0', ['1'] * lmcrs
         elif ans_s=='all':
             sels    = ['1'] * lmcrs
         elif ans_s=='no':
             sels    = ['0'] * lmcrs
         elif ans_s=='imp':
             if '1' not in sels:
                 app.msg_box('Select some names', app.MB_OK)
                 continue
             (good_nms
             ,fail_nms) = self.import_from_list([mcr for (ind, mcr) in enumerate(mcrs) if sels[ind]=='1'])
             l,lt    = '\n', '\n      '
             app.msg_box(   'Import macros:'     +lt+lt.join(good_nms)
                         +l+''
                         +l+'Skip duplicates:'   +lt+lt.join(fail_nms)
                        ,app.MB_OK)
def collect_data():
	''' Collect data
	'''
	keys2nms	= {}
	has_series	= False
	dblkeys		= []
	ctgs		= []
	cmdinfos	= []

	if app_name=='CudaText' and app.app_api_version()>='1.0.212':
		lcmds   = app.app_proc(app.PROC_GET_COMMANDS, '')
		cmdinfos= [('Commands'
				   ,cmd['name']
				   ,cmd['key1']
				   ,cmd['key2']
				   #,cmd['cmd']
				   )
						if cmd['type']=='cmd' else 
				   ('Plugins'
				   ,cmd['name']
				   ,cmd['key1']
				   ,cmd['key2']
				   #,'{},{},{}'.format(cmd['p_module'], cmd['p_method'], cmd['p_method_params']).rstrip(',')
				   )
						for cmd in lcmds
						if cmd['type']!='lexer'
				]
	else: # Syn or old Cud
		n=0
		while True:
			# Cud (5	  ,'smth', 'Shift+Ctrl+F1', 'Alt+Q * Ctrl+T')
			# Syn (5,'ctg','smth', 'Shift+Ctrl+F1', 'Alt+Q · Ctrl+T')
			cmdinfo = app.app_proc(app.PROC_GET_COMMAND, str(n))
			n += 1
			if cmdinfo is None: break
			if cmdinfo[0]<=0: continue
			if app_name=='CudaText':
				# Add default category
				cmdinfo	= ('Commands', cmdinfo[1], cmdinfo[2], cmdinfo[3])
			else:
				cmdinfo	= (cmdinfo[1], cmdinfo[2], cmdinfo[3], cmdinfo[4])

			ctg, name, keys1, keys2 = cmdinfo
			if	name.startswith('lexer:'):		continue	# ?? lexer? smth-more?
			if (app_name=='CudaText' and
				name.startswith('plugin:')):	continue	# ?? plugin? smth-more?
			if (app_name=='SynWrite' and
				ctg=='Plugin'):
				cmdinfo	= (ctg, 'Plugin: '+name, keys1, keys2)

			cmdinfos += [cmdinfo]
		if app_name=='CudaText':
			cmdinfos = add_cud_plugins(cmdinfos, 'plugin: ', 'Plugins')

	for ctg, name, keys1, keys2 in cmdinfos:
		if ctg not in ctgs:
			ctgs += [ctg]
		for keys in (keys1, keys2):
			if not keys: continue
			if srs_dlm in keys:
				# Series: Alt+Q * Ctrl+T
				# It will be parsed later when all single keys are done
				has_series = True
				continue # see Repeat...
			else:
				btn	= ('+'+keys).split('+')[-1]					# 'B' 			 	from 'Shift+Ctrl+B'
				save_btn_mod_name(
					btn
				,	keys[:-len(btn)].rstrip('+')				# 'Shift+Ctrl'		from 'Shift+Ctrl+B'
				,	name, keys
				,	mods, btns, keys2nms, dblkeys
				)

	# Repeat to parse series
	for ctg, name, keys1, keys2 in cmdinfos:
		for keys in (keys1, keys2):
			if srs_dlm not in keys: continue
			# Series: Alt+Q * Ctrl+T
			# 1. Check a conflict with head
			#	(Alt+)(Q)
			keys_hd  = keys.split(srs_dlm)[0]					# 'Alt+Q'			from 'Alt+Q * Ctrl+T'
			if keys_hd in keys2nms:
				# Conflict!
				dblkeys 			+= [keys_hd]
				keys2nms[keys_hd]	+= [name]
			# 2. Save as
			#	(Alt+Q * Ctrl+)(T)
			btn	= ('+'+keys.split(srs_dlm)[-1]).split('+')[-1]	# 'T' 				from 'Alt+Q * Ctrl+T' or 'Alt+Q * T'
			save_btn_mod_name(
				btn
			,	keys[:-len(btn)].rstrip('+')					# 'Alt+Q * Ctrl'	from 'Alt+Q * Ctrl+T'
			,	name, keys
			,	mods, btns, keys2nms, dblkeys
			)
	
	return 	(keys2nms
			,has_series
			,dblkeys
			,ctgs
			,cmdinfos)
import cudatext as app

NEW = app.app_api_version() >= '1.0.275'
MAX_LEN = 500

def get_line(ed, n):
    if NEW:
        return ed.get_text_line(n, MAX_LEN)
    else:
        return ed.get_text_line(n)
Example #38
0
def _check_API(ver):
    if app.app_api_version()<ver:
        app.msg_status(NEED_NEWER_API)
        return False
    return True
Example #39
0
    def dlg_export(self):
        ''' Show dlg for export some macros.
        '''
        if app.app_api_version() < FROM_API_VERSION:
            return app.msg_status('Need update CudaText')
        if 0 == len(self.macros): return app.msg_status('No macros for export')
        exp_file = app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros')
        exp_file = '' if exp_file is None else exp_file
        exp_file = exp_file + ('' if '' == exp_file
                               or exp_file.endswith('.cuda-macros') else
                               '.cuda-macros')
        (WD_LST, HT_LST) = (500, 500)

        lmcrs = len(self.macros)
        crt, sels = '0', ['0'] * lmcrs
        while True:
            pass
            LOG and log('sels={}', sels)
            ans = app.dlg_custom(
                'Export macros',
                GAP + WD_LST + GAP,
                GAP * 5 + HT_LST + 25 * 2,
                '\n'.join([] + [
                    C1.join([
                        'type=label',
                        POS_FMT(l=GAP, t=GAP + 3, r=GAP +
                                70, b=0), 'cap=Export &to'
                    ]  # i=0
                            )
                ] + [
                    C1.join([
                        'type=edit',
                        POS_FMT(l=GAP + 70, t=GAP, r=GAP + WD_LST -
                                35, b=0), 'val={}'.format(exp_file)
                    ]  # i=1
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=GAP + HT_LST - 35,
                                t=GAP - 2,
                                r=GAP + WD_LST,
                                b=0), 'cap=&...'
                    ]  # i=2
                            )
                ] + [
                    C1.join([
                        'type=checklistbox',
                        POS_FMT(l=GAP,
                                t=GAP * 2 + 30,
                                r=GAP + WD_LST,
                                b=GAP + 25 + HT_LST), 'items=' +
                        '\t'.join([mcr['nm'] for mcr in self.macros]), 'val=' +
                        crt + ';' + ','.join(sels)
                    ]  # i=3
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=GAP * 1,
                                t=GAP * 3 + 25 + HT_LST,
                                r=GAP * 1 + 80 * 1,
                                b=0), 'cap=Check &all'
                    ]  # i=4
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=GAP * 2 + 80,
                                t=GAP * 3 + 25 + HT_LST,
                                r=GAP * 2 + 80 * 2,
                                b=0), 'cap=U&ncheck all'
                    ]  # i=5
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=WD_LST - 60 * 2,
                                t=GAP * 3 + 25 + HT_LST,
                                r=WD_LST - 60 * 1,
                                b=0), 'cap=&Export'
                    ]  # i=6
                            )
                ] + [
                    C1.join([
                        'type=button',
                        POS_FMT(l=GAP + WD_LST - 60 * 1,
                                t=GAP * 3 + 25 + HT_LST,
                                r=GAP + WD_LST - 60 * 0,
                                b=0), 'cap=&Close'
                    ]  # i=7
                            )
                ]),
                3)  # start focus
            pass
            LOG and log('ans={}', ans)
            if ans is None: break  #while
            (ans_i, vals) = ans
            ans_s = apx.icase(False, '', ans_i == 2, 'file', ans_i == 4, 'all',
                              ans_i == 5, 'no', ans_i == 6, 'exp', ans_i == 7,
                              'close')
            if ans_s == 'close': break  #while
            v_3 = vals.splitlines()[3]
            crt, sels = v_3.split(';')
            sels = sels.strip(',').split(',')
            pass
            LOG and log('sels={}', sels)
            if False: pass
            elif ans_s == 'file':
                new_exp_file = app.dlg_file(False, '', '',
                                            'Cuda macros|*.cuda-macros')
                if new_exp_file is not None:
                    exp_file = new_exp_file
                    exp_file = exp_file + ('' if '' == exp_file
                                           or exp_file.endswith('.cuda-macros')
                                           else '.cuda-macros')
            elif ans_s == 'all':
                sels = ['1'] * lmcrs
            elif ans_s == 'no':
                sels = ['0'] * lmcrs
            elif ans_s == 'exp':
                if '1' not in sels:
                    app.msg_box('Select some names', app.MB_OK)
                    continue
                self.export_to_file(exp_file, [
                    mcr for (ind, mcr) in enumerate(self.macros)
                    if sels[ind] == '1'
                ])
                return
Example #40
0
    def dlg_config_keys(self):
#       if app.app_api_version()<'1.0.136':     # dlg_hotkey, PROC_GET_HOTKEY, PROC_SET_HOTKEY
        if app.app_api_version()<'1.0.212':     # depr PROC_GET_COMMAND, PROC_GET_COMMAND_PLUGIN
            return app.msg_status(_('Need update CudaText'))
        CfgKeysDlg().show()
    def dlg(self):
        if app.app_api_version()<'1.0.212':     # depr PROC_GET_COMMAND, PROC_GET_COMMAND_PLUGIN
            return app.msg_status(_('Need update CudaText'))
        sndt    = self.sndt
        reND    = re.compile(r'\W')
        def is_cond4name(cond, text):
            if not cond:    return True
            if '_' in cond:
                text    = '·' + reND.sub('·', text) + '·'
                cond   = ' ' + cond + ' '
                cond   = cond.replace(' _', ' ·').replace('_ ', '· ')
            pass;                  #LOG and log('cond, text={}',(cond, text))
            return all(map(lambda cw: cw in text, cond.split()))
        def is_cond4snps(cond, sns_l):
            if not cond:    return  True
            if not sns_l:   return  False
            return any(map(lambda sn:fnmatch(sn, cond), sns_l))
        def bmix(val1, bor2, val2):
            return val1 or val2     if bor2 else        val1 and val2
        cmds_l  = [(cid, sndt.get_name(cid)) for cid in sndt.cmd_ids()]
        
        ccnd_h      = _('Suitable command names will contain all specified words.'
                      '\r · Case is ignored.'
                      '\r · Use "_" for word boundary.'
                      '\r     "_up" selects "upper" but not "group".')
        scnd_h      = _('Suitable command snips will match specified string.'
                      '\r · Case is important.'
                      '\r · Use ? for any character and * for any fragment.')
        
        cmd_id      = ''
        ccnd        = ''
        scnd        = ''
        orcn        = False
        focused     = 'ccnd'
        while True:
            pass;              #LOG and log('ccnd, scnd={}',(ccnd, scnd))
            cins_l  = [    (cid, cnm, sndt.get_snips(cid)) 
                        for cid, cnm in cmds_l]
            fcins_l = [    (cid, cnm, sns)
                       for (cid, cnm, sns)   in cins_l
                       if  bmix(        not ccnd or is_cond4name(ccnd.upper(), cnm.upper())
                               ,orcn,   not scnd or is_cond4snps(scnd, sns)
                               ) ]
            fi_l    = [     cid
                       for (cid, cnm,  sn) in fcins_l]
            stat    = f(' ({}/{})',len(fcins_l), len(cmds_l))
            itms    = (zip([_('Command')+stat, _('Snip(s)')], map(str, [350, 150]))
                      ,    [ (cnm,                ', '.join(sns)) 
                            for  (cid, cnm, sns) in fcins_l ])
            cnts    =[dict(cid='fltr',tp='bt'  ,tid='scnd'  ,l=5+520+5  ,w=110  ,cap=_('&Filter')       ,props='1'          ) # &f  default
                     ,dict(cid='drop',tp='bt'  ,t=5+50      ,l=5+520+5  ,w=110  ,cap=_('&All')                              ) # &a
                     ,dict(cid='orcn',tp='ch'  ,t=5         ,l=5+300    ,w=40   ,cap=_('&OR')           ,act='1'            ) # &o
                     ,dict(           tp='lb'  ,tid='orcn'  ,l=5+5      ,w=90   ,cap=_('In &Command:')          ,hint=ccnd_h) # &c
                     ,dict(cid='ccnd',tp='ed'  ,t=5+20      ,l=5+5      ,w=150                                              ) #
                     ,dict(           tp='lb'  ,tid='orcn'  ,l=5+350+5  ,w=50   ,cap=_('In &Snip(s):')          ,hint=scnd_h) # &s
                     ,dict(cid='shlp',tp='bt'  ,tid='orcn'  ,l=5+350+5+80,w=20   ,cap=_('&?')                                ) # &?
                     ,dict(cid='scnd',tp='ed'  ,t=5+20      ,l=5+350+5  ,w=100                                              ) #
                     ,dict(cid='lwcs',tp='lvw' ,t=5+50      ,l=5        ,w=520,h=535  ,items=itms       ,props='1'          ) #     grid
                     ,dict(cid='asnp',tp='bt'  ,t=200       ,l=5+520+5  ,w=110  ,cap=_('A&dd Snip')                         ) # &d
                     ,dict(cid='rsnp',tp='bt'  ,t=200+30    ,l=5+520+5  ,w=110  ,cap=_('F&ree Snip(s)')                     ) # &r
                     ,dict(cid='help',tp='bt'  ,t=600-65    ,l=5+520+5  ,w=110  ,cap=_('Hel&p')                             ) # &p 
                     ,dict(cid='-'   ,tp='bt'  ,t=600-35    ,l=5+520+5  ,w=110  ,cap=_('Close')                             ) #  
                    ]
            lwcs_n  = -1    if 0==len(fi_l)          else \
                       0    if cmd_id not in fi_l    else \
                       fi_l.index(cmd_id)
            pass;              #    LOG and log('stat, lwcs_n={}',(stat, lwcs_n))
            vals    =       dict(ccnd=ccnd
                                ,scnd=scnd
                                ,orcn=orcn
                                ,lwcs=lwcs_n)
            pass;                  #LOG and log('in-vals={}',(vals))
            btn, vals, chds = dlg_wrapper(_('Configure "SnipToCall"'), 650-5, 600, cnts, vals, focus_cid=focused)
            pass;                  #LOG and log('an-vals={}',(vals))
            pass;                  #LOG and log('chds={}',(chds))
            if btn is None or btn=='-':    return#while True
            focused = chds[0] if 1==len(chds) else focused
            ccnd    = vals['ccnd'].strip()
            scnd    = vals['scnd'].strip()
            orcn    = vals['orcn']
            lwcs_n  = vals['lwcs']
            cmd_id  = '' if lwcs_n==-1 else fi_l[lwcs_n]
            if False:pass
            elif btn in 'fltr':
                focused = 'lwcs'
            elif btn=='drop':
                ccnd    = ''
                scnd    = ''
                focused = 'ccnd'

            elif btn=='shlp':
                app.msg_box(sndt.snip_help, app.MB_OK)
            elif btn=='help':
                dlg_wrapper(_('Help for "Config SnipToCall"'), 410, 310,
                     [dict(cid='htxt',tp='me'    ,t=5  ,h=300-28,l=5          ,w=400  ,props='1,0,1'  ) #  ro,mono,border
                     ,dict(cid='-'   ,tp='bt'    ,t=5+300-23    ,l=5+400-80   ,w=80   ,cap=_('&Close'))
                     ], dict(htxt=f(_('• In Command.'
                                      '\r{ccnd_h}'
                                      '\r '
                                      '\r• In Snip. '
                                      '\r{scnd_h}'
                                      '\r '), ccnd_h=ccnd_h, scnd_h=scnd_h)
                     ), focus_cid='htxt')
            
            elif btn=='rsnp' and cmd_id:
                cnm     = sndt.get_name(cmd_id)
                snp_l   = sndt.get_snips(cmd_id)
                snps    = ', '.join(snp_l)
                if app.msg_box(f(_('Do you want to remove snip(s) '
                                   '\n    {}'
                                   '\nfor command "{}"?')
                                , snps, cnm), app.MB_OKCANCEL)==app.ID_CANCEL: continue#while
                for snp in snp_l:
                    sndt.free(snp)
                
            elif btn=='asnp' and cmd_id:
                cnm     = sndt.get_name(cmd_id)
                new_sn  = app.dlg_input(f(_('Add snip for "{}"'), cnm), '') 
                if not new_sn:  continue#while
                while not SnipData.is_snip(new_sn):
                    app.msg_status(SnipData.msg_correct_snip)
                    new_sn  = app.dlg_input(f(_('Snip for "{}"'), cnm), new_sn) 
                    if not new_sn:  break
                if not new_sn:  continue#while
                pre_cid = sndt.get_cmdid(new_sn)
                if pre_cid:
                    pre_cnm = sndt.get_name(pre_cid)
                    if app.msg_box(f(_('Snip "{}" is already assigned '
                                       '\nto command "{}".'
                                       '\n'
                                       '\nDo you want to reassign the snip '
                                       '\nto command "{}"?')
                                    , new_sn, pre_cnm, cnm), app.MB_OKCANCEL)==app.ID_CANCEL: continue#while
                sndt.set(new_sn, cmd_id)
    def dlg_config_keys(self):
#       if app.app_api_version()<'1.0.136':     # dlg_hotkey, PROC_GET_HOTKEY, PROC_SET_HOTKEY
        if app.app_api_version()<'1.0.212':     # depr PROC_GET_COMMAND, PROC_GET_COMMAND_PLUGIN
            return app.msg_status(_('Need update CudaText'))
        CfgKeysDlg().show()
Example #43
0
 def dlg_export(self):
     ''' Show dlg for export some macros.
     '''
     if app.app_api_version()<FROM_API_VERSION:  return app.msg_status('Need update CudaText')
     if 0==len(self.macros):                     return app.msg_status('No macros for export')
     exp_file= app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros')
     exp_file= '' if exp_file is None else exp_file
     exp_file= exp_file+('' if ''==exp_file or exp_file.endswith('.cuda-macros') else '.cuda-macros')
     (WD_LST
     ,HT_LST)= (500
               ,500)
     
     lmcrs   = len(self.macros)
     crt,sels= '0', ['0'] * lmcrs
     while True:
         pass;               LOG and log('sels={}',sels)
         ans = app.dlg_custom('Export macros'   ,GAP+WD_LST+GAP, GAP*5+HT_LST+25*2, '\n'.join([]
         +[C1.join(['type=label'         ,POS_FMT(l=GAP,             t=GAP+3,            r=GAP+70,     b=0)
                   ,'cap=Export &to'
                   ] # i=0
          )]
         +[C1.join(['type=edit'         ,POS_FMT(l=GAP+70,           t=GAP,              r=GAP+WD_LST-35,b=0)
                   ,'val={}'.format(exp_file)
                   ] # i=1
          )]
         +[C1.join(['type=button'        ,POS_FMT(l=GAP+HT_LST-35,   t=GAP-2,            r=GAP+WD_LST,   b=0)
                   ,'cap=&...'
                   ] # i=2
          )]
         +[C1.join(['type=checklistbox' ,POS_FMT(l=GAP,             t=GAP*2+30,          r=GAP+WD_LST,   b=GAP+25+HT_LST)
                   ,'items=' +'\t'.join([mcr['nm'] for mcr in self.macros])
                   ,'val='   + crt+';'+','.join(sels)
                   ] # i=3
          )]
         +[C1.join(['type=button'        ,POS_FMT(l=GAP*1,           t=GAP*3+25+HT_LST,  r=GAP*1+80*1,   b=0)
                   ,'cap=Check &all'
                   ] # i=4
          )]
         +[C1.join(['type=button'        ,POS_FMT(l=GAP*2+80,        t=GAP*3+25+HT_LST,  r=GAP*2+80*2,   b=0)
                   ,'cap=U&ncheck all'
                   ] # i=5
          )]
         +[C1.join(['type=button'        ,POS_FMT(l=    WD_LST-60*2, t=GAP*3+25+HT_LST,  r=    WD_LST-60*1,   b=0)
                   ,'cap=&Export'
                   ] # i=6
          )]
         +[C1.join(['type=button'        ,POS_FMT(l=GAP+WD_LST-60*1, t=GAP*3+25+HT_LST,  r=GAP+WD_LST-60*0,   b=0)
                   ,'cap=&Close'
                   ] # i=7
          )]
         ), 3)    # start focus
         pass;               LOG and log('ans={}',ans)
         if ans is None:  break #while
         (ans_i
         ,vals)  = ans
         ans_s   = apx.icase(False,''
                    ,ans_i==2, 'file'
                    ,ans_i==4, 'all'
                    ,ans_i==5, 'no'
                    ,ans_i==6, 'exp'
                    ,ans_i==7, 'close'
                    )
         if ans_s=='close':  break #while
         v_3     = vals.splitlines()[3]
         crt,sels= v_3.split(';')
         sels    = sels.strip(',').split(',')
         pass;               LOG and log('sels={}',sels)
         if False:pass
         elif ans_s=='file':
             new_exp_file= app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros')
             if new_exp_file is not None:
                 exp_file    = new_exp_file
                 exp_file    = exp_file+('' if ''==exp_file or exp_file.endswith('.cuda-macros') else '.cuda-macros')
         elif ans_s=='all':
             sels    = ['1'] * lmcrs
         elif ans_s=='no':
             sels    = ['0'] * lmcrs
         elif ans_s=='exp':
             if '1' not in sels:
                 app.msg_box('Select some names', app.MB_OK)
                 continue
             self.export_to_file(exp_file, [mcr for (ind, mcr) in enumerate(self.macros) if sels[ind]=='1'])
             return
Example #44
0
def dlg_valign_consts():
    pass;                      #log('ok')
    UP      = '/\\'
    UP      = '↑↑'
#   UP      = 'ΛΛΛ'
    DN      = '\\/'
    DN      = '↓↓'
#   DN      = 'VVV'
    DLG_W,  \
    DLG_H   = 335, 280
    fits    = dict(
               _sp1=fit_top_by_env('check')
              ,_sp2=fit_top_by_env('edit')
              ,_sp3=fit_top_by_env('button')
              ,_sp4=fit_top_by_env('combo_ro')
              ,_sp5=fit_top_by_env('combo')
              ,_sp6=fit_top_by_env('checkbutton')
              ,_sp7=fit_top_by_env('linklabel')
              ,_sp8=fit_top_by_env('spinedit')
              )
    vals    = dict(
               ch1 =False
              ,ed2 ='=======?'
              ,cbo4=0
              ,cb5 ='=======?'
              ,chb6=0
              ,sp8 =4444444
              )
    focused = '-'
    while True:
        aid, vals, fid, chds = dlg_wrapper(_('Adjust vertical alignments')   ,DLG_W, DLG_H, 
            [dict(cid='lb1'     ,tp='lb'    ,t= 10              ,l=  5  ,w=100  ,cap='==============='                          )
            ,dict(cid='ch1'     ,tp='ch'    ,t= 10+fits['_sp1'] ,l=115  ,w=100  ,cap='=======?'             ,hint=fits['_sp1']  )
            ,dict(cid='up1'     ,tp='bt'    ,t= 10-3            ,l=230  ,w=50   ,cap=UP                                         )
            ,dict(cid='dn1'     ,tp='bt'    ,t= 10-3            ,l=280  ,w=50   ,cap=DN                                         )
                
            ,dict(cid='lb2'     ,tp='lb'    ,t= 40              ,l=  5  ,w=100  ,cap='==============='                          )
            ,dict(cid='ed2'     ,tp='ed'    ,t= 40+fits['_sp2'] ,l=115  ,w=100                              ,hint=fits['_sp2']  )
            ,dict(cid='up2'     ,tp='bt'    ,t= 40-3            ,l=230  ,w=50   ,cap=UP                                         )
            ,dict(cid='dn2'     ,tp='bt'    ,t= 40-3            ,l=280  ,w=50   ,cap=DN                                         )
                
            ,dict(cid='lb3'     ,tp='lb'    ,t= 70              ,l=  5  ,w=100  ,cap='==============='                          )
            ,dict(cid='bt3'     ,tp='bt'    ,t= 70+fits['_sp3'] ,l=115  ,w=100  ,cap='=======?'             ,hint=fits['_sp3']  )
            ,dict(cid='up3'     ,tp='bt'    ,t= 70-3            ,l=230  ,w=50   ,cap=UP                                         )
            ,dict(cid='dn3'     ,tp='bt'    ,t= 70-3            ,l=280  ,w=50   ,cap=DN                                         )
                
            ,dict(cid='lb4'     ,tp='lb'    ,t=100              ,l=  5  ,w=100  ,cap='==============='                          )
            ,dict(cid='cbo4'    ,tp='cb-ro' ,t=100+fits['_sp4'] ,l=115  ,w=100  ,items=['=======?']         ,hint=fits['_sp4']  )
            ,dict(cid='up4'     ,tp='bt'    ,t=100-3            ,l=230  ,w=50   ,cap=UP                                         )
            ,dict(cid='dn4'     ,tp='bt'    ,t=100-3            ,l=280  ,w=50   ,cap=DN                                         )
                
            ,dict(cid='lb5'     ,tp='lb'    ,t=130              ,l=  5  ,w=100  ,cap='==============='                          )
            ,dict(cid='cb5'     ,tp='cb'    ,t=130+fits['_sp5'] ,l=115  ,w=100  ,items=['=======?']         ,hint=fits['_sp5']  )
            ,dict(cid='up5'     ,tp='bt'    ,t=130-3            ,l=230  ,w=50   ,cap=UP                                         )
            ,dict(cid='dn5'     ,tp='bt'    ,t=130-3            ,l=280  ,w=50   ,cap=DN                                         )
                
            ,dict(cid='lb6'     ,tp='lb'    ,t=160              ,l=  5  ,w=100  ,cap='==============='                          )
            ,dict(cid='chb6'    ,tp='ch-bt' ,t=160+fits['_sp6'] ,l=115  ,w=100  ,cap='=======?'             ,hint=fits['_sp6']  )
            ,dict(cid='up6'     ,tp='bt'    ,t=160-3            ,l=230  ,w=50   ,cap=UP                                         )
            ,dict(cid='dn6'     ,tp='bt'    ,t=160-3            ,l=280  ,w=50   ,cap=DN                                         )
                
            ,dict(cid='lb7'     ,tp='lb'    ,t=190              ,l=  5  ,w=100  ,cap='==============='                          )
            ,dict(cid='chb7'    ,tp='ln-lb' ,t=190+fits['_sp7'] ,l=115  ,w=100  ,cap='=======?',props='-'   ,hint=fits['_sp7']  )
            ,dict(cid='up7'     ,tp='bt'    ,t=190-3            ,l=230  ,w=50   ,cap=UP                                         )
            ,dict(cid='dn7'     ,tp='bt'    ,t=190-3            ,l=280  ,w=50   ,cap=DN                                         )
                
            ,dict(cid='lb8'     ,tp='lb'    ,t=220              ,l=  5  ,w=100  ,cap='4444444444444444'                         )
            ,dict(cid='sp8'     ,tp='sp-ed' ,t=220+fits['_sp8'] ,l=115  ,w=100  ,props='0,4444444,1'        ,hint=fits['_sp8']  )
            ,dict(cid='up8'     ,tp='bt'    ,t=220-3            ,l=230  ,w=50   ,cap=UP                                         )
            ,dict(cid='dn8'     ,tp='bt'    ,t=220-3            ,l=280  ,w=50   ,cap=DN                                         )
                
            ,dict(cid='save'    ,tp='bt'    ,t=DLG_H-30         ,l=115  ,w=100  ,cap=_('&Save')
                                                                                ,hint=_('Apply the fittings to controls of all dialogs.'
                                                                                        '\rCtrl+Click  - Show data to mail report.'))
            ,dict(cid='-'       ,tp='bt'    ,t=DLG_H-30         ,l=230  ,w=100  ,cap=_('Cancel')        )
            ], vals, focus_cid=focused)
        if aid is None or aid=='-':    return#while True
        scam        = app.app_proc(app.PROC_GET_KEYSTATE, '') if app.app_api_version()>='1.0.143' else ''
        aid_m       = scam + '/' + aid if scam and scam!='a' else aid   # smth == a/smth
        focused = chds[0] if 1==len(chds) else focused
        if aid[:2]=='up' or aid[:2]=='dn':
            pos = aid[2]
            fits['_sp'+pos] = fits['_sp'+pos] + (-1 if aid[:2]=='up' else 1)
            
        if aid_m=='save':
            ctrls   = ['check'
                      ,'edit'
                      ,'button'   
                      ,'combo_ro' 
                      ,'combo'    
                      ,'checkbutton'
                      ,'linklabel'
                      ,'spinedit'
                      ]
            for ic, nc in enumerate(ctrls):
                fit = fits['_sp'+str(1+ic)]
                if fit==fit_top_by_env(nc): continue#for ic, nc
                apx.set_opt('dlg_wrapper_fit_va_for_'+nc, fit)
               #for ic, nc
            fit_top_by_env__clear()
            break#while
            
        if aid_m=='c/save': # Report
            rpt = 'env:'+get_desktop_environment()
            rpt+= c13+'check:'      +str(fits['_sp1'])
            rpt+= c13+'edit:'       +str(fits['_sp2'])
            rpt+= c13+'button:'     +str(fits['_sp3'])
            rpt+= c13+'combo_ro:'   +str(fits['_sp4'])
            rpt+= c13+'combo:'      +str(fits['_sp5'])
            rpt+= c13+'checkbutton:'+str(fits['_sp6'])
            rpt+= c13+'linklabel:'  +str(fits['_sp7'])
            rpt+= c13+'spinedit:'   +str(fits['_sp8'])
            aid_r, *_t = dlg_wrapper(_('Report'), 230,310,
                 [dict(cid='rprt',tp='me'    ,t=5   ,l=5 ,h=200 ,w=220)
                 ,dict(           tp='lb'    ,t=215 ,l=5        ,w=220  ,cap=_('Send the report to the address'))
                 ,dict(cid='mail',tp='ed'    ,t=235 ,l=5        ,w=220)
                 ,dict(           tp='lb'    ,t=265 ,l=5        ,w=150  ,cap=_('or post it on'))
                 ,dict(cid='gith',tp='ln-lb' ,t=265 ,l=155      ,w=70   ,cap='GitHub',props='https://github.com/kvichans/cuda_fit_v_alignments/issues')
                 ,dict(cid='-'   ,tp='bt'    ,t=280 ,l=205-80   ,w=80   ,cap=_('Close'))
                 ], dict(rprt=rpt
                        ,mail='*****@*****.**'), focus_cid='rprt')
import string as _string
import cudatext as _ct

if _ct.app_api_version() < '1.0.114':
  _ct.msg_box('Hilite Occurrences needs newer app version', _ct.MB_OK + _ct.MB_ICONWARNING)

#----------------------Settings---------------------#
MIN_LEN  = 1 # For word or selected text.
MAX_SIZE = 0 # In bytes. Not used yet.

CHARS = _string.ascii_letters + _string.digits + '_'

SEL_ALLOW             = True  # Hilite all occurrences of selected text.
SEL_ALLOW_WHITE_SPACE = False # Hilite spaces there located in begin or end of selection
SEL_CASE_SENSITIVE    = False
SEL_WORDS_ONLY        = False # Hilite character only if it containts in CHARS.
SEL_WHOLE_WORDS       = False # Whole word only. Used only if bool(SEL_WORDS_ONLY) == True.

CARET_ALLOW          = True # Hilite all occurrences of word under caret.
CARET_CASE_SENSITIVE = True
CARET_WHOLE_WORDS    = True # Whole word only.

COLOR_FONT_OTHER   = 0x000000
COLOR_BG_OTHER     = 0x80FFFF
COLOR_FONT_CURRENT = COLOR_FONT_OTHER
COLOR_BG_CURRENT   = 0xe3c1e3
#-----------------------------------------------#

MARKTAG = 101 #uniq value for all markers plugins

class Command: