<commit_before>/* eslint-disable no-unused-vars, no-use-before-define */
import {
  ipcRenderer as ipc,
  webFrame,
  remote,
  shell,
} from 'electron';

import { openVCardWindow } from './vcard';

import { executeCellInNotebook, formatForJupyter } from './components/notebook'

import * as path from 'path';

import * as fs from 'fs';

import * as uuid from 'uuid';

import React, { PureComponent } from 'react';

import {
  load,
  newNotebook,
} from './epics/loading';

import {
  loadConfig,
} from './epics/config';

import {
  executeCell,
  clearOutputs,
  newKernel,
  killKernel,
  interruptKernel,
  findKernelsReply,
  copyCell,
  cutCell,
  pasteCell,
  createCellAfter,
  setGithubToken,
  changeInputVisibility,
  setTheme,
  setCursorBlink,
  save,
  saveAs,
} from './actions';

import {
  defaultPathFallback,
  cwdKernelFallback,
} from './path';

export function dispatchSaveAs(store, evt, filename) {
  const state = store.getState();
  const notebook = state.document.get('notebook');
  store.dispatch(saveAs(filename, notebook));
}

export function dispatchExportJupyter(store, evt, filename) {
  const state = store.getState();
  const notebook = state.document.get('notebook');
  store.dispatch(save(filename, formatForJupyter(notebook)));
}

const dialog = remote.dialog;

export function showSaveAsDialog() {
  return new Promise((resolve) => {
    const opts = Object.assign({
      title: 'Save Notebook',
      filters: [{ name: 'Notebooks', extensions: ['ipynb'] }],
    }, defaultPathFallback());

    const filename = dialog.showSaveDialog(opts);

    if (filename && path.extname(filename) === '') {
      resolve(`${filename}.ipynb`);
    }
    resolve(filename);
  });
}

export function triggerWindowRefresh(store, filename) {
  if (!filename) {
    return;
  }
  const state = store.getState();
  const notebook = state.document.get('notebook');
  store.dispatch(saveAs(filename, notebook));
}

export function dispatchRestartKernel(store) {
  const state = store.getState();
  const notificationSystem = state.app.get('notificationSystem');

  let cwd = cwdKernelFallback();
  if (state && state.document && state.metadata.get('filename')) {
    cwd = path.dirname(path.resolve(state.metadata.filename));
  }

  store.dispatch(killKernel);
  store.dispatch(newKernel(state.app.kernelSpec, cwd));

  notificationSystem.addNotification({
    title: 'Kernel Restarted',
    message: `Kernel ${state.app.kernelSpecDisplayName} has been restarted.`,
    dismissible: true,
    position: 'tr',
    level: 'success',
  });
}

export function triggerKernelRefresh(store) {
  return new Promise((resolve) => {
    dialog.showMessageBox({
      type: 'question',
      buttons: ['Launch New Kernel', 'Don\'t Launch New Kernel'],
      title: 'New Kernel Needs to Be Launched',
      message: 'It looks like you\'ve saved your notebook file to a new location.',
      detail: 'The kernel executing your code thinks your notbook is still in the ' +
        'old location. Would you like to launch a new kernel to match it with the ' +
        'new location of the notebook?',
    }, (index) => {
      if (index === 0) {
        dispatchRestartKernel(store);
      }
      resolve();
    });
  });
}

export function triggerSaveAs(store) {
  showSaveAsDialog()
    .then((filename) => {
      triggerWindowRefresh(store, filename);
      triggerKernelRefresh(store);
    });
}

export function dispatchSave(store) {
  const state = store.getState();
  const notebook = state.document.get('notebook');
  const filename = state.metadata.get('filename');
  const notificationSystem = state.app.get('notificationSystem');
  try {
    if (!filename) {
      triggerSaveAs(store);
    } else {
      store.dispatch(save(filename, notebook));
    }
    notificationSystem.addNotification({
      title: 'Save successful!',
      autoDismiss: 2,
      level: 'success',
    });
  } catch (err) {
    notificationSystem.addNotification({
      title: 'Save failed!',
      message: err.message,
      level: 'error',
    });
  }
}

export function dispatchNewKernel(store, evt, spec) {
  const state = store.getState();
  let cwd = cwdKernelFallback();
  if (state && state.document && state.metadata.get('filename')) {
    cwd = path.dirname(path.resolve(state.metadata.get('filename')));
  }
  store.dispatch(newKernel(spec, cwd));
}

export function dispatchPublishAnonGist(store) {
  store.dispatch({ type: 'PUBLISH_ANONYMOUS_GIST' });
}

export function dispatchPublishUserGist(store, event, githubToken) {
  if (githubToken) {
    store.dispatch(setGithubToken(githubToken));
  }
  store.dispatch({ type: 'PUBLISH_USER_GIST' });
}

/**
 * Redux dispatch function to run the focused cell and all cells below it.
 * It obtains the focused cell cell id and all code cell cell ids below.
 * It dispatches the {@link executeCell} action on all of those retrieved cells.
 *
 * @exports
 * @param {Object} store - The Redux store
 */
export function dispatchRunAllBelow(store) {
  const state = store.getState();
  const focusedCellId = state.document.get('cellFocused');
  const notebook = state.document.get('notebook');
  const indexOfFocusedCell = notebook.get('cellOrder').indexOf(focusedCellId);
  const cellsBelowFocusedId = notebook.get('cellOrder').skip(indexOfFocusedCell);
  const cells = notebook.get('cellMap');

  cellsBelowFocusedId.filter(cellID =>
    cells.getIn([cellID, 'cell_type']) === 'code')
      .map(cellID => executeCellInNotebook(store, cellID, cells.get(cellID)));
}

export function dispatchRunAll(store) {
  const state = store.getState();
  const notebook = state.document.get('notebook');
  const cells = notebook.get('cellMap');
  notebook.get('cellOrder').filter(cellID =>
    cells.getIn([cellID, 'cell_type']) === 'code')
      .map(cellID => executeCellInNotebook(store, cellID, cells.get(cellID)));
}

export function dispatchClearAll(store) {
  const state = store.getState();
  const notebook = state.document.get('notebook');
  notebook.get('cellOrder').map(value => store.dispatch(clearOutputs(value)));
}

export function dispatchUnhideAll(store) {
  const state = store.getState();
  const notebook = state.document.get('notebook');
  const cells = notebook.get('cellMap');
  notebook.get('cellOrder')
    .filter(cellID => cells.getIn([cellID, 'metadata', 'inputHidden']))
    .map(cellID => store.dispatch(changeInputVisibility(cellID)));
}

export function dispatchKillKernel(store) {
  store.dispatch(killKernel);
}

export function dispatchInterruptKernel(store) {
  const state = store.getState();
  const notificationSystem = state.app.get('notificationSystem');
  if (process.platform === 'win32') {
    notificationSystem.addNotification({
      title: 'Not supported in Windows',
      message: 'Kernel interruption is currently not supported in Windows.',
      level: 'error',
    });
  } else {
    store.dispatch(interruptKernel);
  }
}

export function dispatchRestartClearAll(store) {
  dispatchRestartKernel(store);
  dispatchClearAll(store);
}

function discoverKernels() {

}

export class Spinneret extends PureComponent {
  props: {show: false};

  constructor(): void {
    super();

    this.props = {
      show: false,
    };
  }

  render(): React.Element<any> {
    return (
        this.props.show ?
        <div className="spinner">
          <div className="bounce1"></div>
          <div className="bounce2"></div>
          <div className="bounce3"></div>
        </div>
        : null
    );
  }
}

export function dispatchFindKernelsReply(store, specs, uid) {
  console.log('dispatchFindKernelsReply ', uid);
  store.dispatch( findKernelsReply(specs, uid) );
}

function getPathForSpec(spec) {
  // hack that sometimes works
  return spec.argv ?
    (spec.argv.length > 0 ? spec.argv[0] : '')
    : '';
}

export class FindKernelsControls extends PureComponent {
  state: {
    showSpinner: false,
    showOkayButton: false,
    showCancelButton: false,
    showSearchButton: true,
    showManualButton: false,
  };
  props: {
    identity: '',
    kernel_specs: [],
  };

  constructor(): void {
    super();

    this.state = {
      showSpinner: false,
      showOkayButton: false,
      showCancelButton: false,
      showSearchButton: true,
      showManualButton: false,
    };
    this.searchAction = this.searchAction.bind(this);

    this.props = {
      identity: '',
      kernel_specs: [],
    };
  }

  searchAction(event): void {
    event.stopPropagation();
    this.setState({
      showSpinner: true,
      showOkayButton: false,
      showCancelButton: false,
      showSearchButton: false,
      showManualButton: false,
    });
    ipc.send('find_kernels', this.props.identity);<commit_msg>fix warning<commit_after>/* eslint-disable no-unused-vars, no-use-before-define */
import {
  ipcRenderer as ipc,
  webFrame,
  remote,
  shell,
} from 'electron';

import { openVCardWindow } from './vcard';

import { executeCellInNotebook, formatForJupyter } from './components/notebook'

import * as path from 'path';

import * as fs from 'fs';

import * as uuid from 'uuid';

import React, { PureComponent } from 'react';

import {
  load,
  newNotebook,
} from './epics/loading';

import {
  loadConfig,
} from './epics/config';

import {
  executeCell,
  clearOutputs,
  newKernel,
  killKernel,
  interruptKernel,
  findKernelsReply,
  copyCell,
  cutCell,
  pasteCell,
  createCellAfter,
  setGithubToken,
  changeInputVisibility,
  setTheme,
  setCursorBlink,
  save,
  saveAs,
} from './actions';

import {
  defaultPathFallback,
  cwdKernelFallback,
} from './path';

export function dispatchSaveAs(store, evt, filename) {
  const state = store.getState();
  const notebook = state.document.get('notebook');
  store.dispatch(saveAs(filename, notebook));
}

export function dispatchExportJupyter(store, evt, filename) {
  const state = store.getState();
  const notebook = state.document.get('notebook');
  store.dispatch(save(filename, formatForJupyter(notebook)));
}

const dialog = remote.dialog;

export function showSaveAsDialog() {
  return new Promise((resolve) => {
    const opts = Object.assign({
      title: 'Save Notebook',
      filters: [{ name: 'Notebooks', extensions: ['ipynb'] }],
    }, defaultPathFallback());

    const filename = dialog.showSaveDialog(opts);

    if (filename && path.extname(filename) === '') {
      resolve(`${filename}.ipynb`);
    }
    resolve(filename);
  });
}

export function triggerWindowRefresh(store, filename) {
  if (!filename) {
    return;
  }
  const state = store.getState();
  const notebook = state.document.get('notebook');
  store.dispatch(saveAs(filename, notebook));
}

export function dispatchRestartKernel(store) {
  const state = store.getState();
  const notificationSystem = state.app.get('notificationSystem');

  let cwd = cwdKernelFallback();
  if (state && state.document && state.metadata.get('filename')) {
    cwd = path.dirname(path.resolve(state.metadata.filename));
  }

  store.dispatch(killKernel);
  store.dispatch(newKernel(state.app.kernelSpec, cwd));

  notificationSystem.addNotification({
    title: 'Kernel Restarted',
    message: `Kernel ${state.app.kernelSpecDisplayName} has been restarted.`,
    dismissible: true,
    position: 'tr',
    level: 'success',
  });
}

export function triggerKernelRefresh(store) {
  return new Promise((resolve) => {
    dialog.showMessageBox({
      type: 'question',
      buttons: ['Launch New Kernel', 'Don\'t Launch New Kernel'],
      title: 'New Kernel Needs to Be Launched',
      message: 'It looks like you\'ve saved your notebook file to a new location.',
      detail: 'The kernel executing your code thinks your notbook is still in the ' +
        'old location. Would you like to launch a new kernel to match it with the ' +
        'new location of the notebook?',
    }, (index) => {
      if (index === 0) {
        dispatchRestartKernel(store);
      }
      resolve();
    });
  });
}

export function triggerSaveAs(store) {
  showSaveAsDialog()
    .then((filename) => {
      triggerWindowRefresh(store, filename);
      triggerKernelRefresh(store);
    });
}

export function dispatchSave(store) {
  const state = store.getState();
  const notebook = state.document.get('notebook');
  const filename = state.metadata.get('filename');
  const notificationSystem = state.app.get('notificationSystem');
  try {
    if (!filename) {
      triggerSaveAs(store);
    } else {
      store.dispatch(save(filename, notebook));
    }
    notificationSystem.addNotification({
      title: 'Save successful!',
      autoDismiss: 2,
      level: 'success',
    });
  } catch (err) {
    notificationSystem.addNotification({
      title: 'Save failed!',
      message: err.message,
      level: 'error',
    });
  }
}

export function dispatchNewKernel(store, evt, spec) {
  const state = store.getState();
  let cwd = cwdKernelFallback();
  if (state && state.document && state.metadata.get('filename')) {
    cwd = path.dirname(path.resolve(state.metadata.get('filename')));
  }
  store.dispatch(newKernel(spec, cwd));
}

export function dispatchPublishAnonGist(store) {
  store.dispatch({ type: 'PUBLISH_ANONYMOUS_GIST' });
}

export function dispatchPublishUserGist(store, event, githubToken) {
  if (githubToken) {
    store.dispatch(setGithubToken(githubToken));
  }
  store.dispatch({ type: 'PUBLISH_USER_GIST' });
}

/**
 * Redux dispatch function to run the focused cell and all cells below it.
 * It obtains the focused cell cell id and all code cell cell ids below.
 * It dispatches the {@link executeCell} action on all of those retrieved cells.
 *
 * @exports
 * @param {Object} store - The Redux store
 */
export function dispatchRunAllBelow(store) {
  const state = store.getState();
  const focusedCellId = state.document.get('cellFocused');
  const notebook = state.document.get('notebook');
  const indexOfFocusedCell = notebook.get('cellOrder').indexOf(focusedCellId);
  const cellsBelowFocusedId = notebook.get('cellOrder').skip(indexOfFocusedCell);
  const cells = notebook.get('cellMap');

  cellsBelowFocusedId.filter(cellID =>
    cells.getIn([cellID, 'cell_type']) === 'code')
      .map(cellID => executeCellInNotebook(store, cellID, cells.get(cellID)));
}

export function dispatchRunAll(store) {
  const state = store.getState();
  const notebook = state.document.get('notebook');
  const cells = notebook.get('cellMap');
  notebook.get('cellOrder').filter(cellID =>
    cells.getIn([cellID, 'cell_type']) === 'code')
      .map(cellID => executeCellInNotebook(store, cellID, cells.get(cellID)));
}

export function dispatchClearAll(store) {
  const state = store.getState();
  const notebook = state.document.get('notebook');
  notebook.get('cellOrder').map(value => store.dispatch(clearOutputs(value)));
}

export function dispatchUnhideAll(store) {
  const state = store.getState();
  const notebook = state.document.get('notebook');
  const cells = notebook.get('cellMap');
  notebook.get('cellOrder')
    .filter(cellID => cells.getIn([cellID, 'metadata', 'inputHidden']))
    .map(cellID => store.dispatch(changeInputVisibility(cellID)));
}

export function dispatchKillKernel(store) {
  store.dispatch(killKernel);
}

export function dispatchInterruptKernel(store) {
  const state = store.getState();
  const notificationSystem = state.app.get('notificationSystem');
  if (process.platform === 'win32') {
    notificationSystem.addNotification({
      title: 'Not supported in Windows',
      message: 'Kernel interruption is currently not supported in Windows.',
      level: 'error',
    });
  } else {
    store.dispatch(interruptKernel);
  }
}

export function dispatchRestartClearAll(store) {
  dispatchRestartKernel(store);
  dispatchClearAll(store);
}

function discoverKernels() {

}

export class Spinneret extends PureComponent {
  props: {show: false};

  constructor(): void {
    super();

//     this.props = {
//       show: false,
//     };
  }

  render(): React.Element<any> {
    return (
        this.props.show ?
        <div className="spinner">
          <div className="bounce1"></div>
          <div className="bounce2"></div>
          <div className="bounce3"></div>
        </div>
        : null
    );
  }
}

export function dispatchFindKernelsReply(store, specs, uid) {
  console.log('dispatchFindKernelsReply ', uid);
  store.dispatch( findKernelsReply(specs, uid) );
}

function getPathForSpec(spec) {
  // hack that sometimes works
  return spec.argv ?
    (spec.argv.length > 0 ? spec.argv[0] : '')
    : '';
}

export class FindKernelsControls extends PureComponent {
  state: {
    showSpinner: false,
    showOkayButton: false,
    showCancelButton: false,
    showSearchButton: true,
    showManualButton: false,
  };
  props: {
    identity: '',
    kernel_specs: [],
  };

  constructor(): void {
    super();

    this.state = {
      showSpinner: false,
      showOkayButton: false,
      showCancelButton: false,
      showSearchButton: true,
      showManualButton: false,
    };
    this.searchAction = this.searchAction.bind(this);

//     this.props = {
//       identity: '',
//       kernel_specs: [],
//     };
  }

  searchAction(event): void {
    event.stopPropagation();
    this.setState({
      showSpinner: true,
      showOkayButton: false,
      showCancelButton: false,
      showSearchButton: false,
      showManualButton: false,
    });
    ipc.send('find_kernels', this.props.identity);
{'fraction_non_alphanumeric': 0.1362776025236593, 'fraction_numerical': 0.0010324060797246917, 'mean_word_length': 3.7678424938474158, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 45, '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': '3701926', 'n_tokens_mistral': 5321, 'n_tokens_neox': 5264, 'n_words': 1224}