<commit_before>"""Run Porcupine."""

import argparse
import logging
import os
import platform
from queue import Empty         # queue is a handy variable name
import sys
import tkinter as tk

import porcupine.editor
from porcupine import dirs, _ipc, _logs, _pluginloader, settings, tabs, utils

__all__ = ['main']

log = logging.getLogger(__name__)


def open_content(editor, content, path=None):
    """
    Open a tab with the specified content.
    """
    tab = tabs.FileTab(editor.tabmanager, content, path=path)

    utils.copy_bindings(editor, tab.textwidget)
    return editor.tabmanager.add_tab(tab)


def queue_opener(editor, queue):
    try:
        path, contents = queue.get(block=False)
    except Empty:
        # We still want to pass, not return, here because we need to schedule
        # the next call.
        pass
    else:
        # We utilize the no-exception else so that in any case there's a file
        # or whatever the Porcupine window is focused. This allows sending
        # FOCUS without actually opening any file.
        utils.get_root().focus_set()
        while True:
            if contents is not None:
                open_content(editor, contents, path)

            # We purposefully only get the next one at the end so we can do the
            # trick where we focus if there's anything in the queue.
            try:
                path, contents = queue.get(block=False)
            except Empty:
                break

    editor.after(200, queue_opener, editor, queue)


def main():
    # sys.argv[0] is '__main__.py', so we can't use that as the prog.
    # these hard-coded progs are wrong in some situations, but at least
    # better than '__main__.py'.
    if platform.system() == 'Windows':
        prog = 'py -m porcupine'
    else:
        prog = '%s -m porcupine' % os.path.basename(sys.executable)

    parser = argparse.ArgumentParser(
        prog=prog, description=porcupine.__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        '-v', '--version', action='version',
        version=("Porcupine %s" % porcupine.__version__),
        help="display the Porcupine version number and exit")
    parser.add_argument(
        'file', metavar='FILES', nargs=argparse.ZERO_OR_MORE,
        type=argparse.FileType("r"),
        help="open these files when the editor starts, - means stdin")
    parser.add_argument(
        '--verbose', action='store_true',
        help="print same debugging messages to stderr as to log file")
    parser.add_argument(
        '--shuffle-plugins', action='store_true',
        help=("respect setup_after, but otherwise setup the plugins "
              "in a random order instead of alphabetical order"))
    args = parser.parse_args()

    filelist = []

    for f in args.file:
        if f == sys.stdin:
            filelist.append((None, f.read()))
        else:
            filelist.append((f.name, f.read()))

    try:
        if filelist:
            _ipc.send(filelist)
            print("The", ("file" if len(filelist) == 1 else "files"),
                  "will be opened in the already running Porcupine.")
        else:
            # see comments in queue_opener()<commit_msg>use absolute paths and close files<commit_after>"""Run Porcupine."""

import argparse
import logging
import os
import platform
from queue import Empty         # queue is a handy variable name
import sys
import tkinter as tk

import porcupine.editor
from porcupine import dirs, _ipc, _logs, _pluginloader, settings, tabs, utils

__all__ = ['main']

log = logging.getLogger(__name__)


def open_content(editor, content, path=None):
    """
    Open a tab with the specified content.
    """
    tab = tabs.FileTab(editor.tabmanager, content, path=path)

    utils.copy_bindings(editor, tab.textwidget)
    return editor.tabmanager.add_tab(tab)


def queue_opener(editor, queue):
    try:
        path, contents = queue.get(block=False)
    except Empty:
        # We still want to pass, not return, here because we need to schedule
        # the next call.
        pass
    else:
        # We utilize the no-exception else so that in any case there's a file
        # or whatever the Porcupine window is focused. This allows sending
        # FOCUS without actually opening any file.
        utils.get_root().focus_set()
        while True:
            if contents is not None:
                open_content(editor, contents, path)

            # We purposefully only get the next one at the end so we can do the
            # trick where we focus if there's anything in the queue.
            try:
                path, contents = queue.get(block=False)
            except Empty:
                break

    editor.after(200, queue_opener, editor, queue)


def main():
    # sys.argv[0] is '__main__.py', so we can't use that as the prog.
    # these hard-coded progs are wrong in some situations, but at least
    # better than '__main__.py'.
    if platform.system() == 'Windows':
        prog = 'py -m porcupine'
    else:
        prog = '%s -m porcupine' % os.path.basename(sys.executable)

    parser = argparse.ArgumentParser(
        prog=prog, description=porcupine.__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        '-v', '--version', action='version',
        version=("Porcupine %s" % porcupine.__version__),
        help="display the Porcupine version number and exit")
    parser.add_argument(
        'file', metavar='FILES', nargs=argparse.ZERO_OR_MORE,
        type=argparse.FileType("r"),
        help="open these files when the editor starts, - means stdin")
    parser.add_argument(
        '--verbose', action='store_true',
        help="print same debugging messages to stderr as to log file")
    parser.add_argument(
        '--shuffle-plugins', action='store_true',
        help=("respect setup_after, but otherwise setup the plugins "
              "in a random order instead of alphabetical order"))
    args = parser.parse_args()

    filelist = []

    for f in args.file:
        with f:
            if f == sys.stdin:
                filelist.append((None, f.read()))
            else:
                filelist.append((os.path.abspath(f.name), f.read()))

    try:
        if filelist:
            _ipc.send(filelist)
            print("The", ("file" if len(filelist) == 1 else "files"),
                  "will be opened in the already running Porcupine.")
        else:
            # see comments in queue_opener()
{'fraction_non_alphanumeric': 0.09828273535725238, 'fraction_numerical': 0.0015332720024532351, 'mean_word_length': 2.4223504721930746, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3267937', 'n_tokens_mistral': 1903, 'n_tokens_neox': 1828, 'n_words': 620}