예제 #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)
예제 #2
0
def collect_keys():
    keys_json   = os.path.join(app.app_path(app.APP_DIR_SETTINGS), 'keys.json')
    keys        = apx._json_loads(open(keys_json).read()) if os.path.isfile(keys_json) else {}

    cmdinfos    = []
    pass;                      #LOG and log('app.app_api_version()={}',(app.app_api_version()))
#   if True: # app.app_api_version()>='1.0.212':
    lcmds       = app.app_proc(app.PROC_GET_COMMANDS, '')
    cmdinfos    = [('Plugins'
                   ,cmd['name']
                   ,cmd['key1']
                   ,cmd['key2']
                   ,f('{},{},{}', cmd['p_module'], cmd['p_method'], cmd['p_method_params']).rstrip(',')
                   )
                        if cmd['type']=='plugin' else 
                   ('Commands'
                   ,cmd['name']
                   ,cmd['key1']
                   ,cmd['key2']
                   ,cmd['cmd']
                   )
                        for cmd in lcmds
                        if cmd['type'] in ('plugin', 'cmd')
#                       if cmd['type']!='lexer'
                ]
    return cmdinfos
예제 #3
0
def get_hotkeys_desc(cmd_id, ext_id=None, keys_js=None, def_ans=''):
    """ Read one or two hotkeys for command 
            cmd_id [+ext_id]
        from 
            settings\keys.json
        Return 
            def_ans                     If no  hotkeys for the command
            'Ctrl+Q'            
            'Ctrl+Q * Ctrl+W'           If one hotkey  for the command
            'Ctrl+Q/Ctrl+T'            
            'Ctrl+Q * Ctrl+W/Ctrl+T'    If two hotkeys for the command
    """
    if keys_js is None:
        keys_json = app.app_path(app.APP_DIR_SETTINGS) + os.sep + 'keys.json'
        keys_js = apx._json_loads(
            open(keys_json).read()) if os.path.exists(keys_json) else {}

    cmd_id = f('{},{}', cmd_id, ext_id) if ext_id else cmd_id
    if cmd_id not in keys_js:
        return def_ans
    cmd_keys = keys_js[cmd_id]
    desc = '/'.join([
        ' * '.join(cmd_keys.get('s1', [])), ' * '.join(cmd_keys.get('s2', []))
    ]).strip('/')
    return desc
예제 #4
0
def collect_keys():
    keys_json   = os.path.join(app.app_path(app.APP_DIR_SETTINGS), 'keys.json')
    keys        = apx._json_loads(open(keys_json).read()) if os.path.isfile(keys_json) else {}

    cmdinfos    = []
    pass;                      #LOG and log('app.app_api_version()={}',(app.app_api_version()))
#   if True: # 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']
                   ,f('{},{},{}', cmd['p_module'], cmd['p_method'], cmd['p_method_params']).rstrip(',')
                   )
                        for cmd in lcmds
                        if cmd['type']!='lexer'
                ]
    return cmdinfos
예제 #5
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)
예제 #6
0
    def __init__(self):
        cmd_nms = [
            nm for nm in dir(cmds)
            if nm.startswith('cCommand_') or nm.startswith('cmd_')
        ]
        cmd_nm2id = {nm: eval('cmds.{}'.format(nm)) for nm in cmd_nms}
        self.CMD_ID2NM = {str(cmd_id): nm for nm, cmd_id in cmd_nm2id.items()}
        if len(self.CMD_ID2NM) < len(cmd_nm2id):
            app.msg_status('Repeated values in cudatext_cmd.py')
        pass
        #LOG and log('cmd_nm2id={}',cmd_nm2id)
        pass
        #LOG and log('CMD_ID2NM={}',self.CMD_ID2NM)

        ver_macros = apx._json_loads(
            open(MACROS_JSON).read()) if os.path.exists(MACROS_JSON) else {
                'ver': JSON_FORMAT_VER,
                'list': []
            }
        if ver_macros['ver'] < JSON_FORMAT_VER:
            # Adapt to new format
            pass
        self.tm_ctrl = ver_macros.get('tm_ctrl', {})
        self.dlg_prs = ver_macros.get('dlg_prs', {})
        self.macros = ver_macros['list']
        self.mcr4id = {str(mcr['id']): mcr for mcr in self.macros}

        self.need_dlg = False
        self.last_mcr_id = 0

        pass
        LOG and log('\n\n\nMacros start', )
    def get_data(self, lexer):

        with open(fn_config, encoding='utf8') as f:
            data = appx._json_loads(f.read())

        for d in data['scopes']:
            key = d.get('scope', '_')
            if lexer_map.get(key, '') == lexer:
                return d
 def _loadSess(self, existing=False):
     ''' See _saveSess for returned data format.
         Params
             existing    Delete path from recent if one doesnot exist
     '''
     sess = apx._json_loads(open(SESS_JSON).read()) if os.path.exists(
         SESS_JSON) else self.dfltSess
     #       sess    = json.loads(open(SESS_JSON).read())        if os.path.exists(SESS_JSON) else self.dfltSess
     rcnt = sess['recent']
     if existing and 0 < len(rcnt):
         sess['recent'] = list(filter(os.path.isfile, rcnt))
     return sess
예제 #9
0
    def _do_acts(self, what='', acts='|save|second|reg|keys|menu|'):
        ''' Use macro list '''
        pass
        #LOG and log('what, acts={}',(what, acts))
        # Save
        if '|save|' in acts:
            open(MACROS_JSON, 'w').write(
                json.dumps(
                    {
                        'ver': JSON_FORMAT_VER,
                        'list': self.macros,
                        'dlg_prs': self.dlg_prs,
                        'tm_ctrl': {
                            'rp_ctrl': self.tm_ctrl.get('rp_ctrl', 1000),
                            'tm_wait': self.tm_ctrl.get('tm_wait', 10)
                        }
                    },
                    indent=4))

        # Secondary data
        if '|second|' in acts:
            self.mcr4id = {str(mcr['id']): mcr for mcr in self.macros}

        # Register new subcommands
        if '|reg|' in acts:
            reg_subs = 'cuda_macros;run;{}'.format('\n'.join(
                'macro: {}\t{}'.format(mcr['nm'], mcr['id'])
                for mcr in self.macros))
            pass
            #LOG and log('reg_subs={}',reg_subs)
            app.app_proc(app.PROC_SET_SUBCOMMANDS, reg_subs)

        # Clear keys.json
        if '|keys|' in acts and ':' in what:
            # Need delete a key 'cuda_macros,run,NNNNN'
            mcr_id = what[1 + what.index(':'):]
            mcr_key = 'cuda_macros,run,{}'.format(mcr_id)
            keys_json = app.app_path(
                app.APP_DIR_SETTINGS) + os.sep + 'keys.json'
            if not os.path.exists(keys_json): return
            keys = apx._json_loads(open(keys_json).read())
            pass
            #LOG and log('??? key={}',mcr_key)
            if keys.pop(mcr_key, None) is not None:
                pass
                #LOG and log('UPD keys.json deleted key={}',mcr_key)
                open(keys_json, 'w').write(json.dumps(keys, indent=2))

        # [Re]Build menu
        if '|menu|' in acts:
            self._adapt_menu()
예제 #10
0
 def _do_acts(self, what='', acts='|save|second|reg|keys|menu|'):
     ''' Use macro list '''
     pass;                  #LOG and log('what, acts={}',(what, acts))
     # Save
     if '|save|' in acts:
         open(MACROS_JSON, 'w').write(json.dumps({
              'ver':JSON_FORMAT_VER
             ,'list':self.macros
             ,'dlg_prs':self.dlg_prs
             ,'tm_ctrl':{'rp_ctrl':self.tm_ctrl.get('rp_ctrl', 1000)
                        ,'tm_wait':self.tm_ctrl.get('tm_wait', 10)}
             }, indent=4))
     
     # Secondary data
     if '|second|' in acts:
         self.mcr4id     = {str(mcr['id']):mcr for mcr in self.macros}
     
     # Register new subcommands
     if '|reg|' in acts:
         reg_subs        = 'cuda_macros;run;{}'.format('\n'.join(
                          'macro: {}\t{}'.format(mcr['nm'],mcr['id']) 
                              for mcr in self.macros)
                          )
         pass;              #LOG and log('reg_subs={}',reg_subs)
         app.app_proc(app.PROC_SET_SUBCOMMANDS, reg_subs)
     
     # Clear keys.json
     if '|keys|' in acts and ':' in what:
         # Need delete a key 'cuda_macros,run,NNNNN'
         mcr_id      = what[1+what.index(':'):]
         mcr_key     = 'cuda_macros,run,{}'.format(mcr_id)
         keys_json   = app.app_path(app.APP_DIR_SETTINGS)+os.sep+'keys.json'
         if not os.path.exists(keys_json): return
         keys        = apx._json_loads(open(keys_json).read())
         pass;              #LOG and log('??? key={}',mcr_key)
         if keys.pop(mcr_key, None) is not None:
             pass;          #LOG and log('UPD keys.json deleted key={}',mcr_key)
             open(keys_json, 'w').write(json.dumps(keys, indent=2))
     
     # [Re]Build menu
     if '|menu|' in acts:
         self._adapt_menu()
예제 #11
0
    def _load(self, path):
        from cudax_lib import _json_loads

        with open(path, 'r', encoding='utf-8') as f:
            txt = f.read()

        # remove stream comments: /* ... */
        if '/*' in txt:
            txt = re.sub('/\*.*?\*/', '', txt, flags=re.DOTALL
                         )  # all done consecutively once, no need to compile
        if '\ ' in txt:  # json chokes on escaped spaces
            txt = txt.replace('\ ', ' ')

        self.j = _json_loads(txt)
        if self.j is None:
            raise Exception(_('Json Error'))
        if 'target' in self.j:
            raise NotImplementedError(_('"target" option is not supported')
                                      )  # work done in ST python-plugin

        self._load_selectors()
예제 #12
0
 def __init__(self):
     cmd_nms         = [nm                               for nm in dir(cmds) 
                         if nm.startswith('cCommand_') or nm.startswith('cmd_')]
     cmd_nm2id       = {nm:eval('cmds.{}'.format(nm))    for nm in cmd_nms}
     self.CMD_ID2NM  = {str(cmd_id):nm                   for nm,cmd_id in cmd_nm2id.items()}
     if len(self.CMD_ID2NM) < len(cmd_nm2id):
         app.msg_status('Repeated values in cudatext_cmd.py')
     pass;                  #LOG and log('cmd_nm2id={}',cmd_nm2id)
     pass;                  #LOG and log('CMD_ID2NM={}',self.CMD_ID2NM)
     
     ver_macros      = apx._json_loads(open(MACROS_JSON).read()) if os.path.exists(MACROS_JSON) else {'ver':JSON_FORMAT_VER, 'list':[]}
     if ver_macros['ver'] < JSON_FORMAT_VER:
         # Adapt to new format
         pass
     self.tm_ctrl    = ver_macros.get('tm_ctrl', {})
     self.dlg_prs    = ver_macros.get('dlg_prs', {})
     self.macros     = ver_macros['list']
     self.mcr4id     = {str(mcr['id']):mcr for mcr in self.macros}
     
     self.need_dlg   = False
     self.last_mcr_id= 0
     
     pass;                   LOG and log('\n\n\nMacros start',)
예제 #13
0
def get_hotkeys_desc(cmd_id, ext_id=None, keys_js=None, def_ans=''):
    """ Read one or two hotkeys for command 
            cmd_id [+ext_id]
        from 
            settings\keys.json
        Return 
            def_ans                     If no  hotkeys for the command
            'Ctrl+Q'            
            'Ctrl+Q * Ctrl+W'           If one hotkey  for the command
            'Ctrl+Q/Ctrl+T'            
            'Ctrl+Q * Ctrl+W/Ctrl+T'    If two hotkeys for the command
    """
    if keys_js is None:
        keys_json   = app.app_path(app.APP_DIR_SETTINGS)+os.sep+'keys.json'
        keys_js     = apx._json_loads(open(keys_json).read()) if os.path.exists(keys_json) else {}

    cmd_id  = f('{},{}', cmd_id, ext_id) if ext_id else cmd_id
    if cmd_id not in keys_js:
        return def_ans
    cmd_keys= keys_js[cmd_id]
    desc    = '/'.join([' * '.join(cmd_keys.get('s1', []))
                       ,' * '.join(cmd_keys.get('s2', []))
                       ]).strip('/')
    return desc
예제 #14
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)
예제 #15
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)
예제 #16
0
def load_vals(opt_dfns:list, lexr_json='', ed_=None, full=False, user_json='user.json')->odict:
    """ Create reformated copy (as odict) of
            definitions data opt_dfns (see load_definitions)
        If ed_ then add
            'fval'
            for some options
        If full==True then append optitions without definition
            but only with
            {   opt:'opt name'
            ,   frm:'int'|'float'|'str'
            ,   uval:<value from user.json>
            ,   lval:<value from lexer*.json>
            }}
        Return
            {'opt name':{  opt:'opt name', frm:
        ?   ,   def:, cmt:, dct:, chp:, tgs:
        ?   ,   uval:<value from user.json>
        ?   ,   lval:<value from lexer*.json>
        ?   ,   fval:<value from ed>
            }}
    """
    user_json       = app.app_path(app.APP_DIR_SETTINGS)+os.sep+user_json
    lexr_def_json   = apx.get_def_setting_dir()         +os.sep+lexr_json
    lexr_json       = app.app_path(app.APP_DIR_SETTINGS)+os.sep+lexr_json
    user_vals       = apx._json_loads(open(user_json    , encoding='utf8').read(), object_pairs_hook=odict) \
                        if  os.path.isfile(user_json)     else {}
    lexr_def_vals   = apx._json_loads(open(lexr_def_json, encoding='utf8').read(), object_pairs_hook=odict) \
                        if  os.path.isfile(lexr_def_json) else {}
    lexr_vals       = apx._json_loads(open(lexr_json    , encoding='utf8').read(), object_pairs_hook=odict) \
                        if  os.path.isfile(lexr_json)     else {}
    pass;                      #LOG and log('lexr_vals={}',(lexr_vals))
    pass;                      #LOG and log('lexr_def_vals={}',(lexr_def_vals))

    # Fill vals for defined opt
    pass;                      #LOG and log('no opt={}',([oi for oi in opt_dfns if 'opt' not in oi]))
    oinf_valed  = odict([(oi['opt'], oi) for oi in opt_dfns])
    for opt, oinf in oinf_valed.items():
        if opt in lexr_def_vals:                                # Correct def-vals for lexer
            oinf['dlx']     = True
            oinf['def']     = lexr_def_vals[opt]
            oinf['jdf']     = oinf['def']
        if opt in user_vals:                                    # Found user-val for defined opt
            oinf['uval']    = user_vals[opt]
        if opt in lexr_vals:                                    # Found lexer-val for defined opt
            oinf['lval']    = lexr_vals[opt]
        if ed_ and opt in apx.OPT2PROP:                         # Found file-val for defined opt
            fval            = ed_.get_prop(apx.OPT2PROP[opt])
            oinf['fval']    =fval

    if full:
        # Append item for non-defined opt
        reFontNm    = re.compile(r'font\w*_name')
        def val2frm(val, opt=''):
            pass;              #LOG and log('opt,val={}',(opt,val))
            return  ('bool'     if isinstance(val, bool)    else
                     'int'      if isinstance(val, int)     else
                     'float'    if isinstance(val, float)   else
                     'json'     if isinstance(val, (list, dict))    else
                     'hotk'     if '_hotkey_' in val        else
                     'font'     if isinstance(val, str)     and
                                   reFontNm.search(val)     else
                     'str')
        for uop,uval in user_vals.items():
            if uop in oinf_valed: continue
            oinf_valed[uop] = odict(
                [   ('opt'  ,uop)
                ,   ('frm'  ,val2frm(uval,uop))
                ,   ('uval' ,uval)
                ]+([('lval' ,lexr_vals[uop])] if uop in lexr_vals else [])
                )
        for lop,lval in lexr_vals.items():
            if lop in oinf_valed: continue
            oinf_valed[lop] = odict(
                [   ('opt'  ,lop)
                ,   ('frm'  ,val2frm(lval,lop))
                ,   ('lval' ,lval)
                ])

    upd_cald_vals(oinf_valed)
    upd_cald_vals(oinf_valed, '+def') if lexr_def_vals else None    # To update oi['jdf'] by oi['def']

    return oinf_valed
예제 #17
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)
예제 #18
0
파일: lsp.py 프로젝트: halfbrained/cuda_lsp
def get_project_lsp_cfg():
    fn_cfg = get_project_lsp_cfg_path()
    if fn_cfg  and  os.path.exists(fn_cfg):
        with open(fn_cfg, 'r', encoding='utf-8') as f:
            return _json_loads(f.read())
예제 #19
0
파일: lsp.py 프로젝트: halfbrained/cuda_lsp
    def _load_config(self):
        global opt_enable_mouse_hover
        global opt_root_dir_source
        global opt_manual_didopen
        global opt_send_change_on_request
        global opt_hover_max_lines
        global opt_hover_additional_commands
        global opt_cudatext_in_py_env
        global opt_lint_type
        global opt_lint_underline_style
        global opt_enable_code_tree
        global opt_tree_types_show

        # general cfg
        if os.path.exists(fn_config):
            with open(fn_config, 'r', encoding='utf-8') as f:
                js = f.read()
            j = _json_loads(js)
            opt_enable_mouse_hover = j.get('enable_mouse_hover', opt_enable_mouse_hover)

            _opt_root_dir_source = j.get('root_dir_source', opt_root_dir_source)
            if not isinstance(_opt_root_dir_source, list):  # convert item to list
                _opt_root_dir_source = [_opt_root_dir_source]
            if all(val in {0, 1, 2} for val in _opt_root_dir_source):
                opt_root_dir_source = _opt_root_dir_source
            else:
                print(f'NOTE: {LOG_NAME}: invalid value of option "root_dir_source"'
                        +f' in {fn_config}, accepted values: 0, 1, 2')

            opt_send_change_on_request = j.get('send_change_on_request', opt_send_change_on_request)
            opt_hover_max_lines = j.get('hover_dlg_max_lines', opt_hover_max_lines)
            opt_hover_additional_commands = j.get('hover_additional_commands', opt_hover_additional_commands)
            opt_cudatext_in_py_env = j.get('cudatext_in_py_env', opt_cudatext_in_py_env)
            opt_lint_type = j.get('lint_type', opt_lint_type)

            opt_enable_code_tree = j.get('enable_code_tree', opt_enable_code_tree)
            opt_tree_types_show = j.get('tree_types_show', opt_tree_types_show)

            _opt_lint_underline_style = j.get('lint_underline_style', opt_lint_underline_style)
            if _opt_lint_underline_style in LINT_STYLE_MAP:
                opt_lint_underline_style = _opt_lint_underline_style

            # hidden,dbg
            opt_manual_didopen = j.get('manual_didopen', None)

            # apply options
            Hint.set_max_lines(opt_hover_max_lines)

        # plugin state
        if os.path.exists(fn_state):
            with open(fn_state, 'r', encoding='utf-8') as f:
                js = f.read()
            j = _json_loads(js)
            STATE.update(j)

        # servers
        _lsp_fns = get_server_cfg_fns()
        if _lsp_fns:
            user_lexids = {}

            for name in _lsp_fns:
                path = os.path.join(dir_settings, name)
                with open(path, 'r', encoding='utf-8') as f:
                    try:
                        j = _json_loads(f.read())
                    except:
                        _path = collapse_path(path)
                        print(f'NOTE: {LOG_NAME}: failed to load server config: {_path}')
                        continue

                # load lex map from config
                langids = j.setdefault('langids', [])
                lexmap = j.get('lexers', {})
                for lex,langid in lexmap.items():
                    langids.append(langid)
                    user_lexids[lex] = langid

                # add cuda/py to python server's PYTHONPATH env
                if opt_cudatext_in_py_env  and  'python' in langids:
                    env_paths = j.setdefault('env_paths', {})
                    py_env_paths = env_paths.setdefault('PYTHONPATH', [])
                    py_env_paths.append(app_path(APP_DIR_PY))

                if not langids:
                    _path = collapse_path(path)
                    print(f'NOTE: {LOG_NAME}: sever config error - no associated lexers: {_path}')
                    continue
                if 'name' not in j:
                    j['name'] = os.path.splitext(name)[0]
                # tree options
                j.setdefault('enable_code_tree', opt_enable_code_tree)
                j.setdefault('tree_types_show', opt_tree_types_show)

                servers_cfgs.append(j)

            update_lexmap(user_lexids) # add user mapping to global map

        if not servers_cfgs:
            _dir_settings = collapse_path(dir_settings)
            print(f'NOTE: {LOG_NAME}: no server configs loaded from "{_dir_settings}"')