Esempio n. 1
0
    def _worker(self, signo):
        with gws.lib.misc.lock(_lockfile) as ok:
            if not ok:
                try:
                    pid = int(gws.read_file(_lockfile))
                except:
                    pid = None
                if not pid or not psutil.pid_exists(pid):
                    gws.log.info(
                        f'MONITOR: locked by dead pid={pid!r}, releasing')
                else:
                    gws.log.info(f'MONITOR: locked by pid={pid!r}')
                    return

            gws.write_file(_lockfile, str(os.getpid()))
            changed = self._poll()

            if not changed:
                return

            for path in changed:
                gws.log.info(f'MONITOR: changed {path!r}')

            # @TODO: smarter reload

            reconf = any(gws.APP_DIR not in path for path in changed)

            gws.log.info(f'MONITOR: begin reload (reconfigure={reconf})')

            if not self._reload(reconf):
                return

        # finally, reload ourselves
        gws.log.info(f'MONITOR: bye bye')
        control.reload('spool')
Esempio n. 2
0
def javascript(root: gws.IRoot, category: str, locale_uid: str = '') -> str:
    if category == 'vendor':
        return gws.read_file(root.specs.bundle_paths('vendor')[0])

    if category == 'util':
        return gws.read_file(root.specs.bundle_paths('util')[0])

    if category == 'app':
        bundles = _load_app_bundles(root)
        lang = locale_uid.split('_')[0]
        modules = bundles[BUNDLE_KEY_MODULES]
        strings = bundles.get(BUNDLE_KEY_STRINGS + '_' + lang) or bundles.get(BUNDLE_KEY_STRINGS + '_' + DEFAULT_LANG)

        js = bundles[BUNDLE_KEY_TEMPLATE]
        js = js.replace('__MODULES__', modules)
        js = js.replace('__STRINGS__', strings)

        return js
Esempio n. 3
0
    def _read(self, path):
        if not path.endswith('.qgz'):
            return gws.read_file(path)

        with zipfile.ZipFile(path) as zf:
            for info in zf.infolist():
                if info.filename.endswith('.qgs'):
                    with zf.open(info, 'rt') as fp:
                        return fp.read()
Esempio n. 4
0
 def compile(self):
     text = gws.read_file(self.path) if self.path else self.text
     try:
         g = {}
         exec(text, g)
         return g['main']
     except Exception as exc:
         raise gws.Error(
             f'py load error: {exc!r} in {self.path!r}') from exc
Esempio n. 5
0
    def load(self):
        text = gws.read_file(self.path) if self.path else self.text

        parser = _Parser()
        chartreux.compile(
            text,
            path=self.path or '<string>',
            commands=parser,
        )

        self.page_size = parser.page_size
        self.map_size = parser.map_size
Esempio n. 6
0
    def caps(self, p: CapsParams):
        """Print the capabilities of a document in JSON format"""

        xml = gws.read_file(p.path)
        mod = gws.import_from_path(f'gws/plugin/qgis/caps.py')
        res = mod.parse(xml)

        js = gws.lib.json2.to_pretty_string(res,
                                            default=_caps_json,
                                            ascii=False)

        if p.out:
            gws.write_file(p.out, js)
            gws.log.info(f'saved to {p.out!r}')
        else:
            print(js)
Esempio n. 7
0
def _parse_cx_config(path):
    paths = {path}
    runtime_exc = []

    def _err(exc, path, line):
        if not runtime_exc:
            runtime_exc.append(
                _syntax_error(path, gws.read_file(path), repr(exc), line))

    def _finder(cur_path, p):
        if not os.path.isabs(p):
            d = os.path.dirname(cur_path)
            p = os.path.abspath(os.path.join(d, p))
        paths.add(p)
        return p

    try:
        tpl = chartreux.compile_path(path,
                                     syntax={
                                         'start': '{{',
                                         'end': '}}'
                                     },
                                     finder=_finder)
    except chartreux.compiler.Error as e:
        raise _syntax_error(path, gws.read_file(e.path), e.message, e.line)

    src = chartreux.call(tpl,
                         context={
                             'true': True,
                             'false': False
                         },
                         error=_err)

    if runtime_exc:
        raise runtime_exc[0]

    _save_intermediate(path, src, 'slon')

    try:
        dct = slon.loads(src, as_object=True)
    except slon.SlonError as e:
        raise _syntax_error(path, src, e.args[0], e.args[2])

    return dct, list(paths)
Esempio n. 8
0
def _enum_images(action):
    dd = action.data_dir
    images = []

    for path in os2.find_files(f'{dd}/png', ext='png'):
        fn = _fnbody(path)
        converted_path = f'{dd}/cnv/{fn}.png'

        if os2.file_mtime(converted_path) < os2.file_mtime(path):
            try:
                # reduce the image palette (20-30 colors work just fine for scanned plans)
                gws.log.debug(f'converting {path!r}')
                img = PIL.Image.open(path)
                img = img.convert('RGBA')
                img = img.convert('P',
                                  palette=PIL.Image.ADAPTIVE,
                                  colors=action.image_quality)
                img.save(converted_path)
                os2.chown(converted_path)

                # copy the pgw along
                pgw = gws.read_file(f'{dd}/png/{fn}.pgw')
                gws.write_file(f'{dd}/cnv/{fn}.pgw', pgw)
            except Exception as e:
                gws.log.error(f'error converting {path!r}: {e}')
                continue

        try:
            palette = _image_palette(converted_path)
        except Exception as e:
            gws.log.error(
                f'error getting palette from {converted_path!r}: {e}')
            continue

        images.append({
            'uid': '_r_' + fn,
            'fname': fn,
            'path': converted_path,
            'palette': palette
        })

    return images
Esempio n. 9
0
    def render(self, tri, notify=None):
        notify = notify or _dummy_fn

        notify('begin_print')

        if self.root.application.developer_option('template.always_reload'):
            if self.path:
                self.text = gws.read_file(self.path)

        parser = _Parser()
        rt = _Runtime(self, tri, notify)

        html = self._do_render(self.text, self.prepare_context(tri.context),
                               parser, rt)

        notify('finalize_print')

        mime = tri.out_mime
        if not mime and self.mimes:
            mime = self.mimes[0]
        if not mime:
            mime = gws.lib.mime.HTML

        if mime == gws.lib.mime.HTML:
            notify('end_print')
            return gws.ContentResponse(mime=mime, content=html)

        if mime == gws.lib.mime.PDF:
            res_path = self._finalize_pdf(tri, html, parser)
            notify('end_print')
            return gws.ContentResponse(path=res_path)

        if mime == gws.lib.mime.PNG:
            res_path = self._finalize_png(tri, html, parser)
            notify('end_print')
            return gws.ContentResponse(path=res_path)

        raise gws.Error(f'invalid output mime: {tri.out_mime!r}')
Esempio n. 10
0
    def caps(self, p: CapsParams):
        """Print the capabilities of a service in JSON format"""

        protocol = None

        if p.type:
            protocol = p.type.lower()
        else:
            u = p.src.lower()
            for s in ('wms', 'wmts', 'wfs'):
                if s in u:
                    protocol = s
                    break

        if not protocol:
            raise gws.Error('unknown service')

        if p.src.startswith(('http:', 'https:')):
            xml = gws.gis.ows.request.get_text(
                p.src,
                protocol=t.cast(gws.OwsProtocol, protocol.upper()),
                verb=gws.OwsVerb.GetCapabilities)
        else:
            xml = gws.read_file(p.src)

        mod = gws.import_from_path(
            f'gws/plugin/ows_provider/{protocol}/caps.py')
        res = mod.parse(xml)

        js = gws.lib.json2.to_pretty_string(res, default=_caps_json)

        if p.out:
            gws.write_file(p.out, js)
            gws.log.info(f'saved to {p.out!r}')
        else:
            print(js)
Esempio n. 11
0
 def handle_describerecord(self, rd: core.Request):
     xml = gws.read_file(
         gws.dirname(__file__) + '/templates/describeRecord.xml')
     return gws.ContentResponse(content=xml, mime=gws.lib.mime.XML)
Esempio n. 12
0
 def _err(exc, path, line):
     if not runtime_exc:
         runtime_exc.append(
             _syntax_error(path, gws.read_file(path), repr(exc), line))
Esempio n. 13
0
 def configure(self):
     if self.path:
         self.text = gws.read_file(self.path)
     self.load()
Esempio n. 14
0
def from_path(path: str) -> 'Project':
    return from_string(gws.read_file(path), path)