Merge branch 'master' into jl-std-docs-2

This commit is contained in:
Jessica Lord 2015-08-25 06:10:04 -07:00
commit f4783772c5
72 changed files with 118 additions and 15 deletions

View file

@ -1,68 +0,0 @@
## Guías
* [Distribución de aplicaciones](tutorial/application-distribution-es.md)
* [Empaquetamiento de aplicaciones](tutorial/application-packaging-es.md)
* [Utilizando módulos nativos](tutorial/using-native-node-modules-es.md)
* [Depurando el proceso principal](tutorial/debugging-main-process-es.md)
* [Utilizando Selenium y WebDriver](tutorial/using-selenium-and-webdriver-es.md)
* [Extensión DevTools](tutorial/devtools-extension-es.md)
* [Utilizando el plugin pepper flash](tutorial/using-pepper-flash-plugin-es.md)
## Tutoriales
* [Introducción](tutorial/quick-start.md)
* [Integración con el entorno de escritorio](tutorial/desktop-environment-integration.md)
* [Detección del evento en línea/fuera de línea](tutorial/online-offline-events.md)
## API
* [Sinopsis](api/synopsis.md)
* [Proceso](api/process.md)
* [Parámetros CLI soportados (Chrome)](api/chrome-command-line-switches.md)
Elementos DOM customizados:
* [Objeto `File`](api/file-object.md)
* [Etiqueta `<webview>`](api/web-view-tag.md)
* [Función `window.open`](api/window-open.md)
Módulos del proceso principal:
* [app](api/app.md)
* [auto-updater](api/auto-updater.md)
* [browser-window](api/browser-window.md)
* [content-tracing](api/content-tracing.md)
* [dialog](api/dialog.md)
* [global-shortcut](api/global-shortcut.md)
* [ipc (main process)](api/ipc-main-process.md)
* [menu](api/menu.md)
* [menu-item](api/menu-item.md)
* [power-monitor](api/power-monitor.md)
* [power-save-blocker](api/power-save-blocker.md)
* [protocol](api/protocol.md)
* [tray](api/tray.md)
Módulos del renderer (página web):
* [ipc (renderer)](api/ipc-renderer.md)
* [remote](api/remote.md)
* [web-frame](api/web-frame.md)
Módulos de ambos procesos:
* [clipboard](api/clipboard.md)
* [crash-reporter](api/crash-reporter.md)
* [native-image](api/native-image.md)
* [screen](api/screen.md)
* [shell](api/shell.md)
## Desarrollo
* [Guía de estilo](development/coding-style.md)
* [Estructura de directorio](development/source-code-directory-structure.md)
* [Diferencias técnicas con NW.js (anteriormente conocido como node-webkit)](development/atom-shell-vs-node-webkit.md)
* [Sistema de compilación](development/build-system-overview.md)
* [Instrucciones de compilación (Mac)](development/build-instructions-mac.md)
* [Instrucciones de compilación (Windows)](development/build-instructions-windows.md)
* [Instrucciones de compilación (Linux)](development/build-instructions-linux.md)
* [Configurando un servidor de símbolos en el depurador](development/setting-up-symbol-server.md)

View file

@ -1,68 +0,0 @@
## 개발 가이드
* [어플리케이션 배포](tutorial/application-distribution-ko.md)
* [어플리케이션 패키징](tutorial/application-packaging-ko.md)
* [네이티브 node 모듈 사용하기](tutorial/using-native-node-modules-ko.md)
* [메인 프로세스 디버깅하기](tutorial/debugging-main-process-ko.md)
* [Selenium 과 WebDriver 사용하기](tutorial/using-selenium-and-webdriver-ko.md)
* [개발자 콘솔 확장기능](tutorial/devtools-extension-ko.md)
* [Pepper 플래시 플러그인 사용하기](tutorial/using-pepper-flash-plugin-ko.md)
## 튜토리얼
* [시작하기](tutorial/quick-start-ko.md)
* [데스크톱 환경 통합](tutorial/desktop-environment-integration-ko.md)
* [온라인/오프라인 이벤트](tutorial/online-offline-events-ko.md)
## API 레퍼런스
* [개요](api/synopsis-ko.md)
* [프로세스 객체](api/process-ko.md)
* [크롬 Command-Line 스위치 지원](api/chrome-command-line-switches-ko.md)
커스텀 DOM Element:
* [`File` 객체](api/file-object-ko.md)
* [`<webview>` 태그](api/web-view-tag-ko.md)
* [`window.open` 함수](api/window-open-ko.md)
메인 프로세스를 위한 모듈들:
* [app](api/app-ko.md)
* [auto-updater](api/auto-updater-ko.md)
* [browser-window](api/browser-window-ko.md)
* [content-tracing](api/content-tracing-ko.md)
* [dialog](api/dialog-ko.md)
* [global-shortcut](api/global-shortcut-ko.md)
* [ipc (main process)](api/ipc-main-process-ko.md)
* [menu](api/menu-ko.md)
* [menu-item](api/menu-item-ko.md)
* [power-monitor](api/power-monitor-ko.md)
* [power-save-blocker](api/power-save-blocker-ko.md)
* [protocol](api/protocol-ko.md)
* [tray](api/tray-ko.md)
랜더러 프로세스를 위한 모듈들 (웹 페이지):
* [ipc (renderer)](api/ipc-renderer-ko.md)
* [remote](api/remote-ko.md)
* [web-frame](api/web-frame-ko.md)
두 프로세스에서 모두 사용 가능한 모듈들:
* [clipboard](api/clipboard-ko.md)
* [crash-reporter](api/crash-reporter-ko.md)
* [native-image](api/native-image-ko.md)
* [screen](api/screen-ko.md)
* [shell](api/shell-ko.md)
## 개발자용
* [코딩 스타일](development/coding-style-ko.md)
* [소스 코드 디렉터리 구조](development/source-code-directory-structure-ko.md)
* [NW.js와 기술적으로 다른점 (이전 node-webkit)](development/atom-shell-vs-node-webkit-ko.md)
* [빌드 시스템 개요](development/build-system-overview-ko.md)
* [빌드 설명서 (Mac)](development/build-instructions-mac-ko.md)
* [빌드 설명서 (Windows)](development/build-instructions-windows-ko.md)
* [빌드 설명서 (Linux)](development/build-instructions-linux-ko.md)
* [디버거에서 디버그 심볼 서버 설정](development/setting-up-symbol-server-ko.md)

View file

@ -1,46 +0,0 @@
# Accelerator
Accelerator는 키보드 단축키를 표현하는 문자열입니다, 여러 혼합키와 키코드를 `+` 문자를
이용하여 결합할 수 있습니다.
예제:
* `Command+A`
* `Ctrl+Shift+Z`
## 플랫폼에 관련하여 주의할 점
Linux와 Windows에서는 `Command`키가 없으므로 작동하지 않습니다. 대신에 `CommandOrControl`
사용하면 OS X의 `Command`와 Linux, Windows의 `Control` 모두 지원할 수 있습니다.
`Super`키는 Windows와 Linux 에서는 `윈도우`키를, OS X에서는 `Cmd`키로 맵핑됩니다.
## 사용 가능한 혼합키
* `Command` (단축어 `Cmd`)
* `Control` (단축어 `Ctrl`)
* `CommandOrControl` (단축어 `CmdOrCtrl`)
* `Alt`
* `Shift`
* `Super`
## 사용 가능한 전체 키코드
* `0` 부터 `9` 까지
* `A` 부터 `Z` 까지
* `F1` 부터 `F24` 까지
* `~`, `!`, `@`, `#`, `$`, etc 와 같은 구두점 기호들
* `Plus`
* `Space`
* `Backspace`
* `Delete`
* `Insert`
* `Return` (또는 `Enter`)
* `Up`, `Down`, `Left``Right`
* `Home` 그리고 `End`
* `PageUp` 그리고 `PageDown`
* `Escape` (단축어 `Esc`)
* `VolumeUp`, `VolumeDown` 그리고 `VolumeMute`
* `MediaNextTrack`, `MediaPreviousTrack`, `MediaStop` 그리고 `MediaPlayPause`
__키코드는 `단축어`로도 사용할 수 있습니다__

View file

@ -1,117 +0,0 @@
# auto-updater
**이 모듈은 현재 OS X에서만 사용할 수 있습니다.**
Windows 어플리케이션 인스톨러를 생성하려면 [atom/grunt-electron-installer](https://github.com/atom/grunt-electron-installer)를 참고하세요.
`auto-updater` 모듈은 [Squirrel.Mac](https://github.com/Squirrel/Squirrel.Mac) 프레임워크의 간단한 Wrapper입니다.
Squirrel.Mac은 업데이트 설치를 위해 `.app` 폴더에
[codesign](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/codesign.1.html)
툴을 사용한 서명을 요구합니다.
## Squirrel
Squirrel은 어플리케이션이 **안전하고 투명한 업데이트**를 제공할 수 있도록 하는데 초점이 맞춰진 OS X 프레임워크입니다.
Squirrel은 사용자에게 어플리케이션의 업데이트를 알릴 필요 없이 서버가 지시하는 버전을 받아온 후 자동으로 업데이트합니다.
이 기능을 사용하면 Squirrel을 통해 클라이언트의 어플리케이션을 지능적으로 업데이트 할 수 있습니다.
요청시 커스텀 헤더 또는 요청 본문에 인증 정보를 포함시킬 수도 있습니다.
서버에선 이러한 요청을 분류 처리하여 적당한 업데이트를 제공할 수 있습니다.
Squirrel JSON 업데이트 요청시 처리는 반드시 어떤 업데이트가 필요한지 요청의 기준에 맞춰 동적으로 생성되어야 합니다.
Squirrel은 사용해야 하는 업데이트 선택하는 과정을 서버에 의존합니다. [서버 지원](#server-support)을 참고하세요.
Squirrel의 인스톨러는 오류에 관대하게 설계되었습니다. 그리고 업데이트가 유효한지 확인합니다.
## 업데이트 요청
Squirrel은 업데이트 확인을 위해 클라이언트 어플리케이션의 요청은 무시합니다.
Squirrel은 응답을 분석해야 할 책임이 있기 때문에 `Accept: application/json`이 요청 헤더에 추가됩니다.
업데이트 응답과 본문 포맷에 대한 요구 사항은 [Server Support](#server-support)를 참고하세요.
업데이트 요청에는 서버가 해당 어플리케이션이 어떤 버전을 사용해야 하는지 판단하기 위해 *반드시* 버전 식별자를 포함시켜야 합니다.
추가로 OS 버전, 사용자 이름 같은 다른 식별 기준을 포함하여 서버에서 적합한 어플리케이션을 제공할 수 있도록 할 수 있습니다.
버전 식별자와 다른 기준을 특정하는 업데이트 요청 폼을 서버로 전달하기 위한 공통적인 방법으로 쿼리 인자를 사용하는 방법이 있습니다:
```javascript
// On the main process
var app = require('app');
var autoUpdater = require('auto-updater');
autoUpdater.setFeedUrl('http://mycompany.com/myapp/latest?version=' + app.getVersion());
```
## 서버 지원
업데이트를 제공하는 서버는 반드시 클라이언트로부터 받은 [Update Request](#update-requests)를 기반으로 업데이트를 처리할 수 있어야 합니다.
만약 업데이트 요청이 들어오면 서버는 반드시 [200 OK](http://tools.ietf.org/html/rfc2616#section-10.2.1) 상태 코드를 포함한
[업데이트 JSON](#update-json-format)을 본문으로 보내야 합니다.
이 응답을 받으면 Squirrel은 이 업데이트를 다운로드할 것입니다. 참고로 현재 설치된 버전과 서버에서 받아온 새로운 버전이 같아도 상관하지 않고 무조건 받습니다.
업데이트시 버전 중복을 피하려면 서버에서 클라이언트 업데이트 요청에 대해 통보하지 않으면 됩니다.
만약 따로 업데이트가 없다면 [204 No Content](http://tools.ietf.org/html/rfc2616#section-10.2.5) 상태 코드를 반환해야 합니다.
Squirrel은 지정한 시간이 지난 후 다시 업데이트를 확인합니다.
## JSON 포맷 업데이트
업데이트가 사용 가능한 경우 Squirrel은 다음과 같은 구조의 json 데이터를 응답으로 받습니다:
```json
{
"url": "http://mycompany.com/myapp/releases/myrelease",
"name": "My Release Name",
"notes": "Theses are some release notes innit",
"pub_date": "2013-09-18T12:29:53+01:00"
}
```
응답 json 데이터에서 "url" 키는 필수적으로 포함해야 하고 다른 키들은 옵션입니다.
Squirrel은 "url"로 `Accept: application/zip` 헤더와 함께 업데이트 zip 파일을 요청합니다.
향후 업데이트 포맷에 대해 서버에서 적절한 포맷을 반환할 수 있도록 MIME 타입을 `Accept` 헤더에 담아 요청합니다.
`pub_date`은 ISO 8601 표준에 따라 포맷된 날짜입니다.
## Event: error
* `event` Event
* `message` String
업데이트시 에러가 나면 발생하는 이벤트입니다.
## Event: checking-for-update
업데이트를 확인하기 시작할 때 발생하는 이벤트입니다.
## Event: update-available
사용 가능한 업데이트가 있을 때 발생하는 이벤트입니다. 이벤트는 자동으로 다운로드 됩니다.
## Event: update-not-available
사용 가능한 업데이트가 없을 때 발생하는 이벤트입니다.
## Event: update-downloaded
* `event` Event
* `releaseNotes` String
* `releaseName` String
* `releaseDate` Date
* `updateUrl` String
* `quitAndUpdate` Function
업데이트의 다운로드가 완료되었을 때 발생하는 이벤트입니다. `quitAndUpdate()`를 호출하면 어플리케이션을 종료하고 업데이트를 설치합니다.
## autoUpdater.setFeedUrl(url)
* `url` String
`url`을 설정하고 자동 업데이터를 초기화합니다. `url`은 한번 설정되면 변경할 수 없습니다.
## autoUpdater.checkForUpdates()
서버에 새로운 업데이트가 있는지 요청을 보내 확인합니다. API를 사용하기 전에 `setFeedUrl`를 호출해야 합니다.

View file

@ -1,105 +0,0 @@
# 크롬 Command-Line 스위치 지원
다음 Command-Line 스위치들은 크롬 브라우저에서 제공되는 추가 옵션이며 Electron에서도 지원합니다.
[app][app]의 [ready][ready]이벤트가 작동하기 전에 [app.commandLine.appendSwitch][append-switch] API를 사용하면
어플리케이션 내부에서 스위치들을 추가할 수 있습니다:
```javascript
var app = require('app');
app.commandLine.appendSwitch('remote-debugging-port', '8315');
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1');
app.on('ready', function() {
// Your code here
});
```
## --client-certificate=`path`
`path`를 클라이언트 인증서로 설정합니다.
## --ignore-connections-limit=`domains`
`domains` 리스트(`,`로 구분)의 연결 제한을 무시합니다.
## --disable-http-cache
HTTP 요청 캐시를 비활성화 합니다.
## --remote-debugging-port=`port`
지정한 `port`에 HTTP기반의 리모트 디버거를 활성화 시킵니다. (개발자 콘솔)
## --proxy-server=`address:port`
시스템 설정의 프록시 서버를 무시하고 지정한 서버로 연결합니다. HTTP와 HTTPS 요청에만 적용됩니다.
## --proxy-pac-url=`url`
지정한 `url`의 PAC 스크립트를 사용합니다.
## --no-proxy-server
프록시 서버를 사용하지 않습니다. 다른 프록시 서버 플래그 및 설정을 무시하고 언제나 직접 연결을 사용합니다.
## --host-rules=`rules`
Hostname 맵핑 규칙을 설정합니다. (`,`로 분리)
예시:
* `MAP * 127.0.0.1` Forces all hostnames to be mapped to 127.0.0.1
* `MAP *.google.com proxy` Forces all google.com subdomains to be resolved to
"proxy".
* `MAP test.com [::1]:77` Forces "test.com" to resolve to IPv6 loopback. Will
also force the port of the resulting socket address to be 77.
* `MAP * baz, EXCLUDE www.google.com` Remaps everything to "baz", except for
"www.google.com".
이 맵핑은 네트워크 요청시의 endpoint를 지정합니다. (TCP 연결과 직접 연결의 호스트 resolver, http 프록시 연결의 `CONNECT`, `SOCKS` 프록시 연결의 endpoint 호스트)
## --host-resolver-rules=`rules`
`--host-rules` 플래그와 비슷하지만 이 플래그는 host resolver에만 적용됩니다.
[app]: app-ko.md
[append-switch]: app-ko.md#appcommandlineappendswitchswitch-value
[ready]: app-ko.md#event-ready
## --ignore-certificate-errors
인증서 에러를 무시합니다.
## --ppapi-flash-path=`path`
Pepper 플래시 플러그인의 위치를 설정합니다.
## --ppapi-flash-version=`version`
Pepper 플래시 플러그인의 버전을 설정합니다.
## --log-net-log=`path`
Net log 이벤트를 지정한 `path`에 로그로 기록합니다.
## --v=`log_level`
기본 V-logging 최대 활성화 레벨을 지정합니다. 기본값은 0입니다. 기본적으로 양수를 레벨로 사용합니다.
`--v=-1`를 사용하면 로깅이 비활성화 됩니다.
## --vmodule=`pattern`
`--v` 옵션에 전달된 값을 덮어쓰고 모듈당 최대 V-logging 레벨을 지정합니다.
예를 들어 `my_module=2,foo*=3``my_module.*`, `foo*.*`와 같은 파일 이름 패턴을 가진 모든 소스 코드들의 로깅 레벨을 각각 2와 3으로 설정합니다.
슬래시(`/`), 백슬래시(`\`)를 포함하는 모든 패턴은 모듈뿐만 아니라 모든 경로명에 대해서도 테스트 됩니다.
예를 들어 `*/foo/bar/*=2` 표현식은 `foo/bar` 디렉터리 안의 모든 소스 코드의 로깅 레벨을 2로 지정합니다.
모든 크로미움과 관련된 로그를 비활성화하고 어플리케이션의 로그만 활성화 하려면 다음과 같이 코드를 작성하면 됩니다:
```javascript
app.commandLine.appendSwitch('v', -1);
app.commandLine.appendSwitch('vmodule', 'console=0');
```

View file

@ -1,103 +0,0 @@
# clipboard
`clipboard`는 복사/붙여넣기 작업을 수행하는 방법을 제공합니다. 다음 예제는 클립보드에 문자열을 씁니다:
```javascript
var clipboard = require('clipboard');
clipboard.writeText('Example String');
```
X Window 시스템에선 selection 클립보드도 존재합니다. 이를 사용하려면 인자 뒤에 `selection` 문자열을 같이 지정해주어야 합니다:
```javascript
var clipboard = require('clipboard');
clipboard.writeText('Example String', 'selection');
console.log(clipboard.readText('selection'));
```
## clipboard.readText([type])
* `type` String
클립보드 컨텐츠를 `plain text`로 반환합니다.
## clipboard.writeText(text[, type])
* `text` String
* `type` String
클립보드에 `plain text`로 문자열을 씁니다.
## clipboard.readHtml([type])
* `type` String
클립보드 컨텐츠를 `markup`으로 반환합니다.
## clipboard.writeHtml(markup[, type])
* `markup` String
* `type` String
클립보드에 `markup`으로 씁니다.
## clipboard.readImage([type])
* `type` String
클립보드로부터 [NativeImage](native-image-ko.md)로 이미지를 읽어들입니다.
## clipboard.writeImage(image[, type])
* `image` [NativeImage](native-image-ko.md)
* `type` String
클립보드에 `image`를 씁니다.
## clipboard.clear([type])
* `type` String
클립보드에 저장된 모든 컨텐츠를 삭제합니다.
## clipboard.availableFormats([type])
클립보드의 `type`에 해당하는 지원하는 `format`을 문자열로 반환합니다.
## clipboard.has(data[, type])
* `data` String
* `type` String
클립보드가 지정한 `data`의 형식을 지원하는지 확인합니다.
```javascript
var clipboard = require('clipboard');
console.log(clipboard.has('<p>selection</p>'));
```
**알림:** 이 API는 실험적인 기능이며 차후 최신버전에서 제외될 수 있습니다.
## clipboard.read(data[, type])
* `data` String
* `type` String
클립보드로부터 `data`를 읽어들입니다.
**알림:** 이 API는 실험적인 기능이며 차후 최신버전에서 제외될 수 있습니다.
## clipboard.write(data[, type])
* `data` Object
* `text` String
* `html` String
* `image` [NativeImage](native-image.md)
* `type` String
```javascript
var clipboard = require('clipboard');
clipboard.write({text: 'test', html: "<b>test</b>"});
```
`data`를 클립보드에 씁니다.

View file

@ -1,139 +0,0 @@
# content-tracing
`content-trace` 모듈은 Chromium 컨텐츠 모듈단에서 생성된 데이터를 수집하고 추적하는데 사용됩니다.
이 모듈은 웹 인터페이스를 포함하고 있지 않으며 크롬 브라우저에서 `chrome://tracing/` 페이지를 열어 생성된 파일을 로드하면 결과를 볼 수 있습니다.
```javascript
var tracing = require('content-tracing');
tracing.startRecording('*', tracing.DEFAULT_OPTIONS, function() {
console.log('Tracing started');
setTimeout(function() {
tracing.stopRecording('', function(path) {
console.log('Tracing data recorded to ' + path);
});
}, 5000);
});
```
## tracing.getCategories(callback)
* `callback` Function
카테고리 그룹 세트를 가져옵니다. 카테고리 그룹은 도달된 코드 경로를 변경할 수 있습니다.
모든 child 프로세스가 `getCategories` 요청을 받으면 `callback`이 호출되며 인자에 카테고리 그룹의 배열이 전달됩니다.
## tracing.startRecording(categoryFilter, traceOptions, callback)
* `categoryFilter` String
* `traceOptions` String
* `callback` Function
모든 프로세스에서 레코딩을 시작합니다.
레코딩은 지역적으로 즉시 실행됩니다. 그리고 비동기로 child 프로세스는 곧 EnableRecording 요청을 받게 됩니다.
모든 child 프로세스가 `startRecording` 요청을 받으면 `callback`이 호출됩니다.
`categoryFilter`는 어떤 카테고리 그룹이 트레이싱 되어야 하는지 필터링할 수 있습니다.
필터는 `-` 접두사를 통해 특정 카테고리 그룹을 제외할 수 있습니다.
카테고리 패턴은 같은 리스트 내에서 포함과 제외를 함께 사용할 수 없습니다.
예제:
* `test_MyTest*`,
* `test_MyTest*,test_OtherStuff`,
* `"-excluded_category1,-excluded_category2`
`traceOptions`은 어떤 종류의 트레이싱을 사용할 수 있는지 지정하고 콤마로 리스트를 구분합니다.
사용할 수 있는 옵션은 다음과 같습니다:
* `record-until-full`
* `record-continuously`
* `trace-to-console`
* `enable-sampling`
* `enable-systrace`
첫번째부터 3번째까지의 옵션은 추적 레코딩 모드입니다. 이에 따라 상호 배타적입니다.
만약 레코딩 모드가 한 개 이상 지정되면 마지막 지정한 모드만 사용됩니다.
어떤 모드도 설정되지 않았다면 `record-until-full` 모드가 기본으로 사용됩니다.
추적 옵션은 `traceOptions`이 파싱되어 적용되기 전까지 다음과 같은 기본값이 사용됩니다.
`record-until-full`이 기본 모드, `enable-sampling``enable-systrace`옵션은 포함되지 않음
## tracing.stopRecording(resultFilePath, callback)
* `resultFilePath` String
* `callback` Function
모든 프로세스에서 레코딩을 중지합니다.
Child 프로세스는 일반적으로 추적 데이터와 희귀한 플러시 그리고 추적 데이터를 메인 프로세스로 보내는 작업에 대해 캐싱 합니다.
이러한 일을 하는 이유는 IPC를 통해 추적 데이터를 보내는 작업은 매우 비싼 연산을 동반하기 때문입니다.
우리는 추적에 의한 런타임 오버헤드를 피하는 것을 지향합니다.
그래서 트레이싱이 끝나면 모든 child 프로세스에 보류된 추적 데이터를 플러시 할 것인지 물어봅니다.
모든 child 프로세스가 `stopRecording` 요청을 받으면 `callback`에 추적 데이터를 포함한 파일을 전달됩니다.
추적 데이터는 `resultFilePath` 해당 경로가 비어있는 경우에 한 해 해당 경로에 작성되거나 임시 파일에 작성됩니다.
실제 파일 경로는 null이 아닌 이상 `callback`을 통해 전달됩니다.
## tracing.startMonitoring(categoryFilter, traceOptions, callback)
* `categoryFilter` String
* `traceOptions` String
* `callback` Function
모든 프로세스에서 모니터링을 시작합니다.
모니터링은 지역적으로 즉시 시작됩니다. 그리고 이내 자식 프로세스들이 `startMonitoring` 비동기 요청을 받습니다.
모든 자식 프로세스가 `startMonitoring` 요청을 받으면 `callback`이 호출됩니다.
## tracing.stopMonitoring(callback);
* `callback` Function
모든 프로세스에서 모니터링을 중단합니다.
모든 자식 프로세스가 `stopMonitoring` 요청을 받으면 `callback`이 호출됩니다.
## tracing.captureMonitoringSnapshot(resultFilePath, callback)
* `resultFilePath` String
* `callback` Function
현재 모니터링 추적 데이터를 가져옵니다.
Child processes typically are caching trace data and only rarely flush and send
trace data back to the main process. That is because it may be an expensive
operation to send the trace data over IPC, and we would like to avoid unneeded
runtime overhead of tracing. So, to end tracing, we must asynchronously ask all
child processes to flush any pending trace data.
Once all child processes have acked to the `captureMonitoringSnapshot` request,
the `callback` will be invoked with a file that contains the traced data.
## tracing.getTraceBufferUsage(callback)
* `callback` Function
Get the maximum across processes of trace buffer percent full state. When the
TraceBufferUsage value is determined, the `callback` is called.
## tracing.setWatchEvent(categoryName, eventName, callback)
* `categoryName` String
* `eventName` String
* `callback` Function
`callback` will will be called every time the given event occurs on any
process.
## tracing.cancelWatchEvent()
Watch 이벤트를 중단합니다. 만약 추적이 활성화되어 있다면 이 함수는 watch 이벤트 콜백과 race가 일어날 것입니다.
Cancel the watch event. If tracing is enabled, this may race with the watch event callback.

View file

@ -1,60 +0,0 @@
# crash-reporter
다음 예제는 윈격 서버에 어플리케이션 오류 정보를 자동으로 보고하는 예제입니다:
```javascript
crashReporter = require('crash-reporter');
crashReporter.start({
productName: 'YourName',
companyName: 'YourCompany',
submitUrl: 'https://your-domain.com/url-to-submit',
autoSubmit: true
});
```
## crashReporter.start(options)
* `options` Object
* `productName` String, 기본값: Electron
* `companyName` String, 기본값: GitHub, Inc
* `submitUrl` String, 기본값: http://54.249.141.255:1127/post
* Crash Reporter는 POST 방식으로 해당 URL에 전송됩니다.
* `autoSubmit` Boolean, 기본값: true
* true로 지정할 경우 유저의 승인 없이 자동으로 오류를 보고합니다.
* `ignoreSystemCrashHandler` Boolean, 기본값: false
* `extra` Object
* 오류보고 시 같이 보낼 추가 정보를 지정하는 객체입니다.
* 문자열로 된 속성만 정상적으로 보내집니다.
* 중첩 객체는 지원되지 않습니다. (Nested objects are not supported)
다른 crashReporter API들을 사용하기 전에 이 함수를 먼저 호출해야 합니다.
**알림:** OS X에선 Windows와 Linux의 `breakpad`와 달리 새로운 `crashpad` 클라이언트를 사용합니다.
오류 수집 기능을 활성화 시키려면 오류를 수집하고 싶은 메인 프로세스나 랜더러 프로세스에서
`crashReporter.start` 함수를 호출하여 `crashpad`를 초기화 해야합니다.
## crashReporter.getLastCrashReport()
마지막 오류보고의 날짜와 ID를 반환합니다.
이전 오류보고가 없거나 Crash Reporter가 시작되지 않았을 경우 `null`이 반환됩니다.
## crashReporter.getUploadedReports()
모든 업로드된 오류보고를 반환합니다. 각 보고는 날짜와 업로드 ID를 포함하고 있습니다.
# crash-reporter 오류보고 형식
Crash Reporter는 다음과 같은 데이터를 `submitUrl``POST` 방식으로 전송합니다:
* `rept` String - 예시 'electron-crash-service'
* `ver` String - Electron의 버전
* `platform` String - 예시 'win32'
* `process_type` String - 예시 'renderer'
* `ptime` Number
* `_version` String - `package.json`내의 `version` 필드
* `_productName` String - Crash Reporter의 `options` 객체에서 정의한 제품명.
* `prod` String - 기본 제품의 이름. 이 경우 Electron으로 표시됩니다.
* `_companyName` String - Crash Reporter의 `options` 객체에서 정의한 회사명.
* `upload_file_minidump` File - 오류보고 파일
* Crash Reporter의 `options` 객체에서 정의한 `extra` 객체의 속성들.

View file

@ -1,98 +0,0 @@
# dialog
`dialog` 모듈은 네이티브 시스템의 대화 상자를 조작할 때 사용할 수 있는 API입니다.
웹 어플리케이션에서 일반 네이티브 어플리케이션과 같은 사용자 경험을 제공할 수 있습니다.
다음 예제는 파일과 디렉터리를 다중으로 선택하는 대화 상자를 표시하는 예제입니다:
```javascript
var win = ...; // 대화 상자를 사용할 창 객체
var dialog = require('dialog');
console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]}));
```
**OS X 주의**: 대화 상자를 시트처럼 보여지게 하려면 `browserWindow` 인자에 `BrowserWindow` 객체의 참조를 제공하면 됩니다.
## dialog.showOpenDialog([browserWindow], [options], [callback])
* `browserWindow` BrowserWindow
* `options` Object
* `title` String
* `defaultPath` String
* `filters` Array
* `properties` Array - 대화 상자가 사용할 기능(모드)이 담긴 배열입니다.
다음을 포함할 수 있습니다: `openFile`, `openDirectory`, `multiSelections`, `createDirectory`
* `callback` Function
사용할 대화 상자의 기능이 담긴 배열입니다. 다음을 포함할 수 있습니다: `openFile`, `openDirectory`, `multiSelections`, `createDirectory`
작업에 성공하면 유저가 선택한 파일의 경로를 포함한 배열을 반환합니다. 그 외의 경우엔 `undefined`를 반환합니다.
`filters`를 지정하면 유저가 선택 가능한 파일 형식을 지정할 수 있습니다. 예제는 다음과 같습니다:
```javascript
{
filters: [
{ name: 'Images', extensions: ['jpg', 'png', 'gif'] },
{ name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
{ name: 'Custom File Type', extensions: ['as'] }
]
}
```
`callback`이 전달되면 메소드가 비동기로 작동되며 결과는 `callback(filenames)`을 통해 전달됩니다.
Windows와 Linux에선 파일 선택 모드, 디렉터리 선택 모드를 동시에 사용할 수 없습니다.
그래서 이 두 플랫폼에선 `properties``['openFile', 'openDirectory']`로 설정하면 디렉터리 선택 대화 상자가 표시됩니다.
## dialog.showSaveDialog([browserWindow], [options], [callback])
* `browserWindow` BrowserWindow
* `options` Object
* `title` String
* `defaultPath` String
* `filters` Array
* `callback` Function
작업에 성공하면
작업에 성공하면 유저가 선택한 파일의 경로를 포함한 배열을 반환합니다. 그 외의 경우엔 `undefined`를 반환합니다.
`filters`를 지정하면 유저가 저장 가능한 파일 형식을 지정할 수 있습니다. 사용 방법은 `dialog.showOpenDialog``filters` 속성과 같습니다.
`callback`이 전달되면 메소드가 비동기로 작동되며 결과는 `callback(filename)`을 통해 전달됩니다.
## dialog.showMessageBox([browserWindow], options, [callback])
* `browserWindow` BrowserWindow
* `options` Object
* `type` String - `"none"`, `"info"`, `"error"`, `"question"`, `"warning"` 중 하나를 사용할 수 있습니다.
Windows에선 따로 `icon`을 설정하지 않은 이상 "question"과 "info"는 같은 아이콘으로 표시됩니다.
* `buttons` Array - 버튼들의 라벨을 포함한 배열입니다.
* `title` String - 대화 상자의 제목입니다. 몇몇 플랫폼에선 보이지 않을 수 있습니다.
* `message` String - 대화 상자의 본문 내용입니다.
* `detail` String - 메시지의 추가 정보입니다.
* `icon` [NativeImage](native-image-ko.md)
* `cancelId` Integer - 유저가 대화 상자의 버튼을 클릭하지 않고 대화 상자를 취소했을 때 반환되는 버튼의 index입니다.
기본적으로 버튼 리스트가 "cancel" 또는 "no" 라벨을 가지고 있을 때 해당 버튼의 index를 반환합니다. 따로 두 라벨이 지정되지 않은 경우 0을 반환합니다.
OS X와 Windows에선 `cancelId` 지정 여부에 상관없이 "Cancel" 버튼이 언제나 `cancelId`로 지정됩니다.
* `noLink` Boolean - Windows Electron은 "Cancel"이나 "Yes"와 같은 흔히 사용되는 버튼을 찾으려고 시도하고
대화 상자 내에서 해당 버튼을 커맨드 링크처럼 만듭니다. 이 기능으로 앱을 좀 더 Modern Windows 앱처럼 만들 수 있습니다.
이 기능을 원하지 않으면 `noLink`를 true로 지정하면 됩니다.
* `callback` Function
대화 상자를 표시합니다. `browserWindow`를 지정하면 대화 상자가 완전히 닫힐 때까지는 창을 사용할 수 없습니다.
완료시 유저가 선택한 버튼의 index를 반환합니다.
역주: 부정을 표현하는 "아니오", "취소"와 같은 한글 단어는 지원되지 않습니다.
만약 OS X 또는 Windows에서 "확인", "취소"와 같은 순서로 버튼을 지정하게 될 때 Alt + f4로 해당 대화 상자를 끄게 되면 "확인"을 누른걸로 판단되어 버립니다.
이를 해결하려면 "Cancel"을 대신 사용하거나 BrowserWindow API를 사용하여 대화 상자를 직접 구현해야합니다.
`callback`이 전달되면 메소드가 비동기로 작동되며 결과는 `callback(response)`을 통해 전달됩니다.
## dialog.showErrorBox(title, content)
에러 메시지를 보여주는 모달 대화 상자를 표시합니다.
이 API는 `app` 모듈의 `ready` 이벤트가 발생하기 전에 사용할 수 있습니다.
이 메소드는 보통 어플리케이션이 시작되기 전에 특정한 에러를 표시하기 위해 사용됩니다.

View file

@ -11,7 +11,9 @@ var dialog = require('dialog');
console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]}));
```
**Note for OS X**: If you want to present dialogs as sheets, the only thing you have to do is provide a `BrowserWindow` reference in the `browserWindow` parameter.
**Note for OS X**: If you want to present dialogs as sheets, the only thing you
have to do is provide a `BrowserWindow` reference in the `browserWindow`
parameter.
## dialog.showOpenDialog([browserWindow], [options], [callback])
@ -36,17 +38,22 @@ selected, an example is:
filters: [
{ name: 'Images', extensions: ['jpg', 'png', 'gif'] },
{ name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
{ name: 'Custom File Type', extensions: ['as'] }
{ name: 'Custom File Type', extensions: ['as'] },
{ name: 'All Files', extensions: ['*'] }
]
}
```
The `extensions` array should contain extensions without wildcards or dots (e.g.
`'png'` is good, `'.png'` and `'*.png'` are bad). To show all files, use the
`'*'` wildcard (no other wildcard is supported).
If a `callback` is passed, the API call would be asynchronous and the result
would be passed via `callback(filenames)`
**Note:** On Windows and Linux, an open dialog can not be both a file selector
and a directory selector, so if you set `properties` to
`['openFile', 'openDirectory']` on these platforms, a directory selector will be shown.
`['openFile', 'openDirectory']` on these platforms, a directory selector will be
shown.
## dialog.showSaveDialog([browserWindow], [options], [callback])
@ -70,7 +77,9 @@ will be passed via `callback(filename)`
* `browserWindow` BrowserWindow
* `options` Object
* `type` String - Can be `"none"`, `"info"`, `"error"`, `"question"` or `"warning"`. On Windows, "question" displays the same icon as "info", unless if you set an icon using the "icon" option
* `type` String - Can be `"none"`, `"info"`, `"error"`, `"question"` or
`"warning"`. On Windows, "question" displays the same icon as "info", unless
if you set an icon using the "icon" option
* `buttons` Array - Array of texts for buttons
* `title` String - Title of the message box, some platforms will not show it
* `message` String - Content of the message box

View file

@ -1,28 +0,0 @@
# `File` 객체
DOM의 File 인터페이스는 네이티브 파일을 추상화 합니다. 유저가 직접적으로 HTML5 File API를 사용하여 작업할 때 파일의 경로를
알 수 있도록 Electron은 파일시스템의 실제 파일 경로를 담은 `path` 속성을 File 인터페이스에 추가하였습니다.
다음 예제는 drag n drop한 파일의 실제 경로를 가져옵니다:
```html
<div id="holder">
Drag your file here
</div>
<script>
var holder = document.getElementById('holder');
holder.ondragover = function () {
return false;
};
holder.ondragleave = holder.ondragend = function () {
return false;
};
holder.ondrop = function (e) {
e.preventDefault();
var file = e.dataTransfer.files[0];
console.log('File you dragged here is', file.path);
return false;
};
</script>
```

View file

@ -1,75 +0,0 @@
# Frameless 윈도우
Frameless 윈도우는 테두리가 없는 윈도우 창을 말합니다.
## Frameless 윈도우 만들기
Frameless 윈도우를 만드려면 [BrowserWindow](browser-window-ko.md) 객체의 `options`에서 `frame` 옵션을 `false`로 지정하기만 하면됩니다:
```javascript
var BrowserWindow = require('browser-window');
var win = new BrowserWindow({ width: 800, height: 600, frame: false });
```
## 투명한 창 만들기
Frameless 윈도우의 창의 배경을 투명하게 만들고 싶다면 `transparent` 옵션을 `true`로 바꿔주기만 하면됩니다:
```javascript
var win = new BrowserWindow({ transparent: true, frame: false });
```
### API의 한계
* 투명한 영역을 통과하여 클릭할 수 없습니다. 우리는 이 문제를 해결하기 위해 API를 제공할 예정이지만 현재로써는
[upstream 버그](https://code.google.com/p/chromium/issues/detail?id=387234)로 인해 중단된 상태입니다.
* 투명한 창은 크기를 조절할 수 없습니다. `resizable` 속성을 `true`로 할 경우 몇몇 플랫폼에선 윈도우 크래시가 일어납니다.
* `blur` 필터는 웹 페이지에서만 적용됩니다. 윈도우 아래 컨텐츠에는 블러 효과를 적용할 방법이 없습니다.
* Windows에선 DWM(데스크톱 창 관리자)가 비활성화되어 있을 경우 작동하지 않습니다.
* Linux를 사용할 경우 [alpha channel doesn't work on some NVidia drivers](https://code.google.com/p/chromium/issues/detail?id=369209)
upstream 버그가 있으므로 CLI 옵션에 `--enable-transparent-visuals --disable-gpu`을 추가해야 합니다.
이 옵션은 GPU의 사용을 중단하고 윈도우를 생성하는데 ARGB를 사용할 수 있도록 해줍니다.
* OS X(Mac)에선 네이티브 윈도우의 그림자가 투명한 창에선 보이지 않습니다.
## 드래그 가능 위치 지정
기본적으로 Frameless 윈도우는 드래그 할 수 없습니다.
어플리케이션의 CSS에서 특정 범위를 `-webkit-app-region: drag`로 지정하면 OS의 기본 타이틀바 처럼 드래그 되도록 할 수 있습니다.
그리고 `-webkit-app-region: no-drag`를 지정해서 드래그 불가능 영역을 만들 수도 있습니다. 현재 사각형 형태의 범위만 지원합니다.
창 전체를 드래그 가능하게 만드려면 `-webkit-app-region: drag``body`의 스타일에 지정하면 됩니다:
```html
<body style="-webkit-app-region: drag">
</body>
```
참고로 창 전체를 드래그 영역으로 지정할 경우 사용자가 버튼을 클릭할 수 없게 되므로 버튼은 드래그 불가능 영역으로 지정해야 합니다:
```css
button {
-webkit-app-region: no-drag;
}
```
또한 커스텀 타이틀바를 만들어 사용할 때 타이틀바 내부의 버튼도 드래그 불가능 영역으로 지정해야 합니다.
## 텍스트 선택
한가지, Frameless 윈도우에서 텍스트가 선택되는 드래그 동작은 혼란을 야기할 수 있습니다.
예를 들어 타이틀바를 드래그 할 때 타이틀바의 텍스트를 실수로 선택할 수 있습니다.
이를 방지하기 위해선 다음과 같이 드래그 영역의 텍스트 선택 동작을 비활성화해야 할 필요가 있습니다:
```css
.titlebar {
-webkit-user-select: none;
-webkit-app-region: drag;
}
```
## 컨텍스트 메뉴
몇몇 플랫폼에선 드래그 가능 영역이 non-client 프레임으로 처리됩니다. 그래서 이 영역에서 오른쪽 클릭을 할 경우 시스템 메뉴가 팝업 됩니다.
그래서 컨텍스트 메뉴 지정이 모든 플랫폼에서 정상적으로 작동하게 하려면 커스텀 컨텍스트 메뉴를 드래그 영역 내에 만들어선 안됩니다.

View file

@ -1,54 +0,0 @@
# global-shortcut
`global-shortcut` 모듈은 운영체제의 전역 키보드 단축키를 설정 등록/해제 하는 방법을 제공합니다.
이 모듈을 사용하여 사용자가 다양한 단축키 작업을 할 수 있도록 단축키를 정의 할 수 있습니다.
참고로 설정된 단축키는 어플리케이션이 백그라운드로 작동(창이 포커스 되지 않음) 할 때도 여전히 계속 작동합니다.
이 모듈은 `app` 모듈의 `ready` 이벤트 이전에 사용할 수 없습니다.
```javascript
var app = require('app');
var globalShortcut = require('global-shortcut');
app.on('ready', function() {
// 'ctrl+x' 단축키를 리스너에 등록합니다.
var ret = globalShortcut.register('ctrl+x', function() { console.log('ctrl+x is pressed'); })
if (!ret) {
console.log('registration failed');
}
// 단축키가 등록되었는지 확인합니다.
console.log(globalShortcut.isRegistered('ctrl+x'));
});
app.on('will-quit', function() {
// 단축키의 등록을 해제합니다.
globalShortcut.unregister('ctrl+x');
// 모든 단축키의 등록을 해제합니다.
globalShortcut.unregisterAll();
});
```
## globalShortcut.register(accelerator, callback)
* `accelerator` [Accelerator](accelerator-ko.md)
* `callback` Function
`accelerator`로 표현된 전역 단축키를 등록합니다. 유저로부터 등록된 단축키가 눌렸을 경우 `callback` 함수가 호출됩니다.
## globalShortcut.isRegistered(accelerator)
* `accelerator` [Accelerator](accelerator-ko.md)
지정된 `accelerator` 단축키가 등록되었는지 여부를 확인합니다. 반환값은 boolean(true, false) 입니다.
## globalShortcut.unregister(accelerator)
* `accelerator` [Accelerator](accelerator-ko.md)
`키코드`에 해당하는 전역 단축키를 등록 해제합니다.
## globalShortcut.unregisterAll()
모든 전역 단축키 등록을 해제합니다.

View file

@ -1,46 +0,0 @@
# ipc (main process)
랜더러 프로세스(웹 페이지)로 부터 동기 또는 비동기로 메시지를 받아 처리합니다.
랜더러로부터 발신된 메시지들은 모두 이 모듈에서 `channel` 이라는 특정 이벤트 이름을 통해 수신할 수 있습니다.
동기 메시지는 `event.returnValue`를 이용하여 반환값(답장)을 설정할 수 있습니다. 비동기 메시지라면 `event.sender.send(...)`를 사용하면 됩니다.
또한 메인 프로세스에서 랜더러 프로세스로 메시지를 보내는 것도 가능합니다.
자세한 내용은 [WebContents.send](browser-window-ko.md#webcontentssendchannel-args)를 참고 하세요.
보내진 메시지들을 처리하는 예제입니다:
```javascript
// 메인 프로세스에서 처리.
var ipc = require('ipc');
ipc.on('asynchronous-message', function(event, arg) {
console.log(arg); // prints "ping"
event.sender.send('asynchronous-reply', 'pong');
});
ipc.on('synchronous-message', function(event, arg) {
console.log(arg); // prints "ping"
event.returnValue = 'pong';
});
```
```javascript
// 랜더러 프로세스에서의 처리 (web page).
var ipc = require('ipc');
console.log(ipc.sendSync('synchronous-message', 'ping')); // prints "pong"
ipc.on('asynchronous-reply', function(arg) {
console.log(arg); // prints "pong"
});
ipc.send('asynchronous-message', 'ping');
```
## Class: Event
### Event.returnValue
동기 메시지를 설정합니다.
### Event.sender
메시지를 보내온 sender `WebContents` 객체입니다.

View file

@ -1,25 +0,0 @@
# ipc (renderer)
`ipc` 모듈은 메인 프로세스로 메시지를 동기 또는 비동기로 보내고 받을 수 있는 몇 가지 방법을 제공합니다.
만약 랜더러 프로세스에서 메인 프로세스의 모듈을 직접적으로 사용하고 싶다면 [remote](remote-ko.md) 모듈을 사용하는 것을 고려해보는 것이 좋습니다.
[ipc (main process)](ipc-main-process-ko.md)에서 예제를 볼 수 있습니다.
## ipc.send(channel[, args...])
지정한 `channel`을 통해 `args..`를 비동기로 메시지를 보냅니다. 메인 프로세스는 `ipc` 모듈의 `channel` 이벤트를 통해 메시지를 받을 수 있습니다.
## ipc.sendSync(channel[, args...])
지정한 `channel`을 통해 `args..`를 동기로 메시지를 보냅니다. 그리고 메인 프로세스에서 보낸 결과를 반환합니다.
메인 프로세스는 `ipc` 모듈의 `channel` 이벤트를 통해 메시지를 받을 수 있습니다. 그리고 `event.returnValue`를 통해 반환값을 설정할 수 있습니다.
역자 주: `channel`은 이벤트 이름입니다.
**알림:** 보통 개발자들은 해당 API를 사용하려 하지 않습니다. 동기 ipc 작업은 랜더러 프로세스의 모든 작업을 중단시킵니다.
## ipc.sendToHost(channel[, args...])
`ipc.send`와 비슷하지만 메시지를 메인 프로세스 대신 호스트 페이지로 보냅니다.
이 메소드는 보통 `<webview>`와 호스트 페이지 간의 통신에 사용됩니다.

View file

@ -1,20 +0,0 @@
# menu-item
## Class: MenuItem
### new MenuItem(options)
* `options` Object
* `click` Function - 메뉴 아이템이 클릭될 때 호출되는 콜백함수
* `selector` String - First Responder가 클릭될 때 호출 되는 선택자 (OS X 전용)
* `type` String - `MenuItem`의 타입 `normal`, `separator`, `submenu`, `checkbox` 또는 `radio` 사용가능
* `label` String
* `sublabel` String
* `accelerator` [Accelerator](accelerator-ko.md)
* `icon` [NativeImage](native-image-ko.md)
* `enabled` Boolean
* `visible` Boolean
* `checked` Boolean
* `submenu` Menu - 보조메뉴를 설정합니다. `type``submenu`일 경우 반드시 설정해야합니다. 일반 메뉴 아이템일 경우 생략할 수 있습니다.
* `id` String - 현재 메뉴 아이템에 대해 유일키를 지정합니다. 이 키는 이후 `position` 옵션에서 사용할 수 있습니다.
* `position` String - 미리 지정한 `id`를 이용하여 메뉴 아이템의 위치를 세밀하게 조정합니다.

View file

@ -1,131 +0,0 @@
# NativeImage
Electron은 파일 경로나 `NativeImage` 인스턴스를 전달하여 사용하는 이미지 API를 가지고 있습니다. `null`을 전달할 경우 빈 이미지가 사용됩니다.
예를 들어 트레이 메뉴를 만들거나 윈도우의 아이콘을 설정할 때 다음과 같이 `문자열`인 파일 경로를 전달할 수 있습니다:
```javascript
var appIcon = new Tray('/Users/somebody/images/icon.png');
var window = new BrowserWindow({icon: '/Users/somebody/images/window.png'});
```
또는 클립보드로부터 이미지를 읽어올 수 있습니다:
```javascript
var clipboard = require('clipboard');
var image = clipboard.readImage();
var appIcon = new Tray(image);
```
## 지원하는 포맷
현재 `PNG``JPEG` 포맷을 지원하고 있습니다. 손실 없는 이미지 압축과 투명도 지원을 위해 `PNG` 사용을 권장합니다.
## 고해상도 이미지
플랫폼이 high-DPI를 지원하는 경우 `@2x`와 같이 이미지의 파일명 뒤에 접미사를 추가하여 고해상도 이미지로 지정할 수 있습니다.
예를 들어 `icon.png` 라는 기본 해상도의 이미지를 기준으로 크기를 두 배로 늘린 이미지를 `icon@2x.png`와 같이 이름을 지정하면 고해상도 이미지로 처리됩니다.
서로 다른 해상도(DPI)의 이미지를 지원하고 싶다면 다중 해상도의 이미지를 접미사를 붙여 한 폴더에 넣으면 됩니다. 이 이미지를 사용(로드)할 땐 접미사를 붙이지 않습니다:
```text
images/
├── icon.png
├── icon@2x.png
└── icon@3x.png
```
```javascript
var appIcon = new Tray('/Users/somebody/images/icon.png');
```
지원하는 DPI 접미사는 다음과 같습니다:
* `@1x`
* `@1.25x`
* `@1.33x`
* `@1.4x`
* `@1.5x`
* `@1.8x`
* `@2x`
* `@2.5x`
* `@3x`
* `@4x`
* `@5x`
## 템플릿 이미지
템플릿 이미지는 검은색과 명확한 색상(알파 채널)으로 이루어져 있습니다.
템플릿 이미지는 단독 이미지로 사용되지 않고 다른 컨텐츠와 혼합되어 최종 외관 만드는데 사용됩니다.
가장 일반적으로 템플릿 이미지는 밝고 어두운 테마 색상으로 변경할 수 있는 메뉴 바 아이콘 등에 사용되고 있습니다.
템플릿 이미지는 Mac 운영체제만 지원합니다.
템플릿 이미지를 지정하려면 다음 예제와 같이 파일명에 `Template` 문자열을 추가해야 합니다:
* `xxxTemplate.png`
* `xxxTemplate@2x.png`
## nativeImage.createEmpty()
`NativeImage` 인스턴스를 만듭니다.
## nativeImage.createFromPath(path)
* `path` String
`path`로부터 이미지를 로드하여 새로운 `NativeImage` 인스턴스를 만듭니다.
## nativeImage.createFromBuffer(buffer[, scaleFactor])
* `buffer` [Buffer][buffer]
* `scaleFactor` Double
`buffer`로부터 이미지를 로드하여 새로운 `NativeImage` 인스턴스를 만듭니다. `scaleFactor`는 1.0이 기본입니다.
## nativeImage.createFromDataUrl(dataUrl)
* `dataUrl` String
`dataUrl`로부터 이미지를 로드하여 새로운 `NativeImage` 인스턴스를 만듭니다.
## Class: NativeImage
이미지를 표현한 클래스입니다.
### NativeImage.toPng()
`PNG` 이미지를 인코딩한 데이터를 [Buffer][buffer]로 반환합니다.
### NativeImage.toJpeg(quality)
* `quality` Integer (0 - 100 사이의 값)
`JPEG` 이미지를 인코딩한 데이터를 [Buffer][buffer]로 반환합니다.
### NativeImage.toDataUrl()
이미지의 data URL을 반환합니다.
### NativeImage.isEmpty()
이미지가 비었는지를 체크합니다.
### NativeImage.getSize()
이미지의 사이즈를 반환합니다.
### NativeImage.setTemplateImage(option)
* `option` Boolean
해당 이미지를 템플릿 이미지로 설정합니다.
### NativeImage.isTemplateImage()
이미지가 템플릿 이미지인지 확인합니다.
[buffer]: https://iojs.org/api/buffer.html#buffer_class_buffer

View file

@ -1,33 +0,0 @@
# power-monitor
`power-monitor` 모듈은 PC의 파워 상태를 나타냅니다. (주로 노트북 등에서 사용됩니다)
이 모듈은 메인 프로세스에서만 사용할 수 있으며, (remote 모듈(RPC)을 사용해도 작동이 됩니다)
메인 프로세스의 `app` 모듈에서 `ready` 이벤트를 호출하기 전까지 사용할 수 없습니다.
예제:
```javascript
var app = require('app');
app.on('ready', function() {
require('power-monitor').on('suspend', function() {
console.log('절전모드로 진입합니다!');
});
});
```
## Event: suspend
시스템이 절전모드로 진입할 때 발생하는 이벤트입니다.
## Event: resume
시스템의 절전모드가 해제될 때 발생하는 이벤트입니다.
## Event: on-ac
시스템이 AC 어뎁터 충전기를 사용하기 시작할 때 발생하는 이벤트입니다.
## Event: on-battery
시스템이 배터리를 사용하기 시작할 때 발생하는 이벤트입니다.

View file

@ -1,43 +0,0 @@
# power-save-blocker
`power-save-blocker` 모듈은 시스템이 저전력 모드(슬립)로 진입하는 것을 막고 앱 및 화면이 항상 활성화되어 있는 상태를 만들 수 있도록 해줍니다.
예제:
```javascript
var powerSaveBlocker = require('power-save-blocker');
var id = powerSaveBlocker.start('prevent-display-sleep');
console.log(powerSaveBlocker.isStarted(id));
powerSaveBlocker.stop(id);
```
## powerSaveBlocker.start(type)
* `type` String - Power save blocker 종류
* `prevent-app-suspension` - 저전력 모드 등으로 인한 어플리케이션 작동 중단을 방지합니다.
시스템을 항시 활성화 상태로 만듭니다, 하지만 화면은 자동으로 꺼질 수 있습니다. 사용 예시: 파일 다운로드, 음악 재생 등.
* `prevent-display-sleep`- 슬립 모드 등으로 인한 어플리케이션의 작동 중단을 방지합니다.
시스템을 항시 활성화 상태로 만들고 슬립 모드(화면 꺼짐)를 방지합니다. 사용 예시: 비디오 재생 등.
Power save blocker를 시작하고 시스템이 저전력 모드(슬립)로 진입하는 것을 막습니다. 정수로 된 식별 ID를 반환합니다.
**알림:**
`prevent-display-sleep` 모드는 `prevent-app-suspension` 보다 우선순위가 높습니다.
가장 높은 우선순위의 모드만 작동합니다. 다시 말해 `prevent-display-sleep` 모드는 언제나 `prevent-app-suspension` 모드의 효과를 덮어씌웁니다.
예를 들어 A-요청이 `prevent-app-suspension` 모드를 사용하고 B-요청이 `prevent-display-sleep`를 사용하는 API 호출이 있었다 치면
`prevent-display-sleep` 모드를 사용하는 B의 작동이 중단(stop)되기 전까지 작동하다 B가 중단되면 `prevent-app-suspension` 모드를 사용하는 A가 작동하기 시작합니다.
## powerSaveBlocker.stop(id)
* `id` Integer - `powerSaveBlocker.start`로 부터 반환되는 power save blocker 식별 ID.
설정한 power save blocker를 중지합니다.
## powerSaveBlocker.isStarted(id)
* `id` Integer - `powerSaveBlocker.start`로 부터 반환되는 power save blocker 식별 ID.
해당하는 id의 `powerSaveBlocker`가 실행중인지 확인합니다.

View file

@ -1,12 +0,0 @@
# 프로세스 객체
Electron의 `process` 객체는 기존의 node와는 달리 약간의 차이점이 있습니다:
* `process.type` String - 프로세스의 타입, `browser` (메인 프로세스) 또는 `renderer`가 됩니다.
* `process.versions['electron']` String - Electron의 버전.
* `process.versions['chrome']` String - Chromium의 버전.
* `process.resourcesPath` String - JavaScript 소스코드의 경로.
## process.hang
현재 프로세스의 주 스레드를 중단시킵니다.

View file

@ -1,131 +0,0 @@
# protocol
`protocol` 모듈은 여러 프로토콜의 요청과 응답을 커스터마이즈 할 수 있도록 이미 있는 프로토콜을 변경하거나 새로운 프로토콜을 만드는 방법을 제공합니다.
다음 예제는 `file://` 프로토콜과 같은 일을 하는 커스텀 프로토콜을 설정합니다:
```javascript
var app = require('app');
var path = require('path');
app.on('ready', function() {
var protocol = require('protocol');
protocol.registerProtocol('atom', function(request) {
var url = request.url.substr(7)
return new protocol.RequestFileJob(path.normalize(__dirname + '/' + url));
}, function (error, scheme) {
if (!error)
console.log(scheme, ' registered successfully')
});
});
```
**알림:** 이 모듈은 app의 `ready` 이벤트가 발생한 이후에만 사용할 수 있습니다.
## protocol.registerProtocol(scheme, handler, callback)
* `scheme` String
* `handler` Function
* `callback` Function
지정한 `scheme`을 기반으로 커스텀 프로토콜을 등록합니다. `handler`는 등록한 `scheme` 프로토콜에 요청이 들어올 경우 `request` 인자와 함께 `handler(request)` 형식으로 호출됩니다.
`handler` 함수에선 요청에 대한 해당 프로토콜의 작업 결과를 응답(반환) 해야 합니다.
기본적으로 스킴은 `http:`와 비슷합니다. `file:`과 같이 "표준 URI 구문"을 다르게 해석되게 하려면
`protocol.registerStandardSchemes` 메서드를 이용해서 사용자 정의 스킴을 표준 스킴으로 만들 수 있습니다.
## protocol.unregisterProtocol(scheme, callback)
* `scheme` String
* `callback` Function
지정한 `scheme` 프로토콜을 등록 해제합니다.
## protocol.registerStandardSchemes(value)
* `value` Array
지정한 `value` 배열을 사용하여 미리 지정된 표준 스킴으로 등록합니다.
표준 스킴은 RFC 3986 [표준 URI 구문](https://tools.ietf.org/html/rfc3986#section-3)에 해당합니다.
이 표준은 `file:``filesystem:`을 포함합니다.
## protocol.isHandledProtocol(scheme, callback)
* `scheme` String
* `callback` Function
해당 `scheme`에 처리자(handler)가 등록되었는지 확인합니다.
지정한 `callback`에 결과가 boolean 값으로 반환됩니다.
## protocol.interceptProtocol(scheme, handler, callback)
* `scheme` String
* `handler` Function
* `callback` Function
지정한 `scheme`의 작업을 `handler`로 변경합니다.
`handler`에서 `null` 또는 `undefined`를 반환 할 경우 해당 프로토콜의 기본 동작(응답)으로 대체 됩니다.
## protocol.uninterceptProtocol(scheme, callback)
* `scheme` String
* `callback` Function
변경된 프로토콜의 작업을 해제합니다.
## Class: protocol.RequestFileJob(path)
* `path` String
`path` 경로를 기반으로 파일을 반환하는 request 작업을 생성합니다. 그리고 해당 파일에 상응하는 mime type을 지정합니다.
## Class: protocol.RequestStringJob(options)
* `options` Object
* `mimeType` String - 기본값: `text/plain`
* `charset` String - 기본값: `UTF-8`
* `data` String
문자열을 반환하는 request 작업을 생성합니다.
## Class: protocol.RequestBufferJob(options)
* `options` Object
* `mimeType` String - 기본값: `application/octet-stream`
* `encoding` String - 기본값: `UTF-8`
* `data` Buffer
버퍼를 반환하는 request 작업을 생성합니다.
## Class: protocol.RequestHttpJob(options)
* `options` Object
* `session` [Session](browser-window.md#class-session) - 기본적으로 이 옵션은 어플리케이션의 기본 세션입니다.
`null`로 설정하면 요청을 위한 새로운 세션을 만듭니다.
* `url` String
* `method` String - 기본값: `GET`
* `referrer` String
`url`의 요청 결과를 그대로 반환하는 request 작업을 생성합니다.
## Class: protocol.RequestErrorJob(code)
* `code` Integer
콘솔에 특정한 네트워크 에러 메시지를 설정하는 request 작업을 생성합니다.
기본 메시지는 `net::ERR_NOT_IMPLEMENTED`입니다. 사용할 수 있는 코드의 범위는 다음과 같습니다.
* 범위:
* 0- 99 System related errors
* 100-199 Connection related errors
* 200-299 Certificate errors
* 300-399 HTTP errors
* 400-499 Cache errors
* 500-599 ?
* 600-699 FTP errors
* 700-799 Certificate manager errors
* 800-899 DNS resolver errors
에러 코드와 메시지에 대해 자세하게 알아보려면 [네트워크 에러 리스트](https://code.google.com/p/chromium/codesearch#chromium/src/net/base/net_error_list.h)를 참고하기 바랍니다.

View file

@ -1,87 +0,0 @@
# remote
`remote` 모듈은 메인 프로세스와 랜더러 프로세스 사이에 inter-process 통신을 간단하게 추상화 한 모듈입니다.
Electron의 랜더러 프로세스에선 GUI와 관련 없는 모듈만 사용할 수 있습니다.
기본적으로 랜더러 프로세스에서 메인 프로세스의 API를 사용하려면 inter-process 통신을 사용해야 합니다.
하지만 `remote` 모듈을 사용하면 따로 inter-process 통신을 사용하지 않고 직접 명시적으로 사용할 수 있습니다.
Java의 [RMI](http://en.wikipedia.org/wiki/Java_remote_method_invocation)와 개념이 비슷합니다.
다음 예제는 랜더러 프로세스에서 브라우저 창을 만드는 예제입니다:
```javascript
var remote = require('remote');
var BrowserWindow = remote.require('browser-window');
var win = new BrowserWindow({ width: 800, height: 600 });
win.loadUrl('https://github.com');
```
알림: 반대로 하려면(메인 프로세스에서 랜더러 프로세스에 접근) [webContents.executeJavascript](browser-window.md#webcontents-executejavascript-code) API를 사용하면 됩니다.
## Remote 객체
`remote` 모듈로부터 반환된 각 객체(함수 포함)는 메인 프로세스의 객체를 추상화 한 객체입니다. (우리는 그것을 remote 객체 또는 remote 함수라고 부릅니다)
Remote 모듈의 함수를 호출하거나, 객체에 접근하거나, 생성자로 객체를 생성하는 등의 작업은 실질적으로 동기형 inter-process 메시지를 보냅니다.
위의 예제에서 사용한 두 `BrowserWindow``win`은 remote 객체입니다. 그리고 `new BrowserWindow`이 생성하는 `BrowserWindow` 객체는 랜더러 프로세스에서 생성되지 않습니다.
대신에 이 `BrowserWindow` 객체는 메인 프로세스에서 생성되며 랜더러 프로세스에 `win` 객체와 같이 이에 대응하는 remote 객체를 반환합니다.
## Remote 객체의 일생
Electron은 랜더러 프로세스의 remote 객체가 살아있는 한(다시 말해서 GC(garbage collection)가 일어나지 않습니다) 대응하는 메인 프로세스의 객체는 릴리즈되지 않습니다.
Remote 객체가 GC 되려면 대응하는 메인 프로세스 내부 객체의 참조가 해제되어야만 합니다.
만약 remote 객체가 랜더러 프로세스에서 누수가 생겼다면 (예시: 맵에 저장하고 할당 해제하지 않음) 대응하는 메인 프로세스의 객체도 누수가 생깁니다.
그래서 remote 객체를 사용할 땐 메모리 누수가 생기지 않도록 매우 주의해서 사용해야 합니다.
참고로 문자열, 숫자와 같은 원시 값 타입은 복사에 의한 참조로 전달됩니다.
## 메인 프로세스로 콜백 넘기기
몇몇 메인 프로세스의 API는 콜백 함수를 사용합니다. 그리고 보통 remote 함수를 호출할 때 콜백 함수를 넘길 것입니다.
`remote` 모듈은 이를 지원합니다. 하지만 반드시 주의해서 사용해야 합니다.
첫째, 데드락을 피하기 위해 메인 프로세스로 전달된 콜백들은 비동기로 호출됩니다.
그래서 전달된 콜백들이 언제나 값을 반환할 것이라고 기대하면 안 됩니다.
둘째, 콜백들은 메인 프로세스로 전송되고 호출된 후에도 자동으로 참조가 릴리즈 되지 않습니다.
참조는 메인 프로세스에서 GC가 일어나기 전까지 계속 남아있게 됩니다.
다음 코드를 보면 느낌이 팟 하고 올 것입니다. 이 예제는 remote 객체에 `close` 이벤트 콜백을 설치합니다:
```javascript
var remote = require('remote');
remote.getCurrentWindow().on('close', function() {
// blabla...
});
```
문제는 이 이벤트는 명시적으로 제거하지 않는 이상 계속해서 메인 프로세스에 남아있게 된다는 것입니다.
그래서 매 창을 새로고침 할 때마다 콜백이 새롭게 설치되며 이전 콜백은 떨궈져 누수가 됩니다.
설상가상으로 이전에 설치한 콜백의 콘텍스트가 릴리즈 되고 나서 `close` 이벤트가 발생하면 예외가 발생하고 메인 프로세스가 작동 중지됩니다.
일반적으로 정확히 무엇을 할 것인지 잘 알고 있지 않는 이상 웬만하면 메인 프로세스로 콜백 함수를 넘기는 건 자제하는 게 좋습니다.
## remote.require(module)
* `module` String
메인 프로세스의 `require(module)` API를 실행한 후 결과 객체를 반환합니다.
## remote.getCurrentWindow()
현재 웹 페이지가 들어있는 [BrowserWindow](browser-window-ko.md) 객체를 반환합니다.
## remote.getCurrentWebContents()
현재 웹 페이지의 WebContents 객체를 반환합니다.
## remote.getGlobal(name)
* `name` String
메인 프로세스의 전역 변수(`name`)를 가져옵니다. (예시: `global[name]`)
## remote.process
메인 프로세스의 `process` 객체를 반환합니다. `remote.getGlobal('process')`와 같습니다. 하지만 캐시 됩니다.

View file

@ -1,106 +0,0 @@
# screen
`screen` 모듈은 화면 크기, 디스플레이, 커서 위치 등등의 다양한 정보를 가져옵니다.
이 모듈은 `app` 모듈의 `ready` 이벤트가 발생하기 전까지 사용할 수 없습니다.
`screen`은 [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter)를 상속 받았습니다.
한가지 주의할 점은 랜더러 / DevTools에선 이 모듈의 이름인 `screen`은 이미 DOM 속성에 `window.screen`로 존재 하므로 `screen = require('screen')`
사용할 수 없습니다. 밑의 예제와 같이 `atomScreen`등의 이름으로 변수 이름을 대체하여 사용해야 합니다.
다음 예제는 화면 전체를 채우는 윈도우 창을 생성합니다:
```javascript
var app = require('app');
var BrowserWindow = require('browser-window');
var mainWindow;
app.on('ready', function() {
var atomScreen = require('screen');
var size = atomScreen.getPrimaryDisplay().workAreaSize;
mainWindow = new BrowserWindow({ width: size.width, height: size.height });
});
```
다음 예제는 확장 디스플레이에 윈도우를 생성합니다:
```javascript
var app = require('app');
var BrowserWindow = require('browser-window');
var mainWindow;
app.on('ready', function() {
var atomScreen = require('screen');
var displays = atomScreen.getAllDisplays();
var externalDisplay = null;
for (var i in displays) {
if (displays[i].bounds.x > 0 || displays[i].bounds.y > 0) {
externalDisplay = displays[i];
break;
}
}
if (externalDisplay) {
mainWindow = new BrowserWindow({
x: externalDisplay.bounds.x + 50,
y: externalDisplay.bounds.y + 50,
});
}
});
```
## Event: display-added
* `event` Event
* `newDisplay` Object
새로운 디스플레이가 추가되면 발생하는 이벤트입니다.
## Event: display-removed
* `event` Event
* `oldDisplay` Object
기존의 디스플레이가 제거되면 발생하는 이벤트입니다.
## Event: display-metrics-changed
* `event` Event
* `display` Object
* `changedMetrics` Array
`display`의 하나 또는 다수의 매트릭스가 변경될 때 발생하는 이벤트입니다.
`changedMetrics`는 변경에 대한 정보를 담은 문자열의 배열입니다.
`bounds`, `workArea`, `scaleFactor`, `rotation`등이 변경될 수 있습니다.
## screen.getCursorScreenPoint()
현재 마우스 포인터의 절대 위치를 반환합니다.
## screen.getPrimaryDisplay()
기본 디스플레이를 반환합니다.
## screen.getAllDisplays()
사용 가능한 모든 디스플레이를 배열로 반환합니다.
## screen.getDisplayNearestPoint(point)
* `point` Object
* `x` Integer
* `y` Integer
지정한 좌표에 가까운 디스플레이를 반환합니다.
## screen.getDisplayMatching(rect)
* `rect` Object
* `x` Integer
* `y` Integer
* `width` Integer
* `height` Integer
지정한 범위에 가장 가깝게 교차한 디스플레이를 반환합니다.

View file

@ -1,41 +0,0 @@
# shell
`shell` 모듈은 데스크톱 환경 통합에 관련하여 제공되는 모듈입니다.
다음 예제는 기본 브라우저로 설정된 URL을 엽니다:
```javascript
var shell = require('shell');
shell.openExternal('https://github.com');
```
## shell.showItemInFolder(fullPath)
* `fullPath` String
지정한 파일을 탐색기에서 보여줍니다. 가능한 경우 탐색기 내에서 파일을 선택합니다.
## shell.openItem(fullPath)
* `fullPath` String
지정한 파일을 데스크톱 기본 프로그램으로 엽니다.
## shell.openExternal(url)
* `url` String
제공된 외부 프로토콜 URL을 기반으로 데스크톱의 기본 프로그램으로 엽니다. (예를 들어 mailto: URL은 해당 URL을 기본 메일 에이전트로 엽니다.)
역주: 폴더는 'file:\\\\C:\\'와 같이 지정하여 열 수 있습니다. (`\\`로 경로를 표현한 이유는 Escape 문자열을 참고하세요.)
## shell.moveItemToTrash(fullPath)
* `fullPath` String
Move the given file to trash and returns boolean status for the operation.
지정한 파일을 휴지통으로 이동합니다. 작업의 성공여부를 boolean 형으로 리턴합니다.
## shell.beep()
비프음을 재생합니다.

View file

@ -1,39 +0,0 @@
# 개요
Electron은 모든 [node.js's built-in 모듈](http://nodejs.org/api/)과 third-party node 모듈을 완벽하게 지원합니다. ([네이티브 모듈](../tutorial/using-native-node-modules-ko.md)을 포함해서)
Electron은 네이티브 데스크톱 어플리케이션을 개발 할 수 있도록 추가적인 built-in 모듈을 제공합니다.
몇몇 모듈은 메인 프로세스에서만 사용할 수 있고 어떤 모듈은 랜더러 프로세스에서만 사용할 수 있습니다. 또한 두 프로세스 모두 사용할 수 있는 모듈도 있습니다.
기본적인 규칙은 다음과 같습니다: GUI와 저 수준 시스템에 관련된 모듈은 오직 메인 프로세스에서만 사용할 수 있습니다.
[메인 프로세스 vs. 랜더러 프로세스](../tutorial/quick-start-ko.md#메인 프로세스) 컨셉에 익숙해야 이 모듈들을 사용하기 쉬우므로 해당 문서를 정독하는 것을 권장합니다.
메인 프로세스 스크립트는 일반 `node.js` 스크립트와 같습니다:
```javascript
var app = require('app');
var BrowserWindow = require('browser-window');
var window = null;
app.on('ready', function() {
window = new BrowserWindow({width: 800, height: 600});
window.loadUrl('https://github.com');
});
```
웹 페이지 역시 예외적인 node module을 사용할 수 있다는 점을 제외하면 일반 웹 페이지와 다를게 없습니다:
```html
<!DOCTYPE html>
<html>
<body>
<script>
var remote = require('remote');
console.log(remote.require('app').getVersion());
</script>
</body>
</html>
```
어플리케이션을 실행하려면 [앱 실행하기](../tutorial/quick-start-ko.md#앱 실행하기) 문서를 참고하기 바랍니다.

View file

@ -1,190 +0,0 @@
# Tray
`Tray`는 OS의 알림영역에 아이콘을 표시합니다. 보통 컨텍스트 메뉴(context menu)를 같이 사용합니다.
```javascript
var app = require('app');
var Menu = require('menu');
var Tray = require('tray');
var appIcon = null;
app.on('ready', function(){
appIcon = new Tray('/path/to/my/icon'); // 현재 어플리케이션 디렉터리를 기준으로 하려면 `__dirname + '/images/tray.png'` 형식으로 입력해야합니다.
var contextMenu = Menu.buildFromTemplate([
{ label: 'Item1', type: 'radio' },
{ label: 'Item2', type: 'radio' },
{ label: 'Item3', type: 'radio', checked: true },
{ label: 'Item4', type: 'radio' }
]);
appIcon.setToolTip('이것은 나의 어플리케이션 입니다!');
appIcon.setContextMenu(contextMenu);
});
```
__플랫폼별 한계:__
* Linux에서는 앱 알림 표시기(app indicator)가 지원되면 해당 기능을 사용합니다. 만약 지원하지 않으면 `GtkStatusIcon`을 대신 사용합니다.
* Linux 배포판이 앱 알림 표시기만 지원하고 있다면 `libappindicator1`를 설치하여 트레이 아이콘이 작동하도록 만들 수 있습니다.
* 앱 알림 표시기는 컨텍스트 메뉴를 가지고 있을 때만 보입니다.
* Linux에서 앱 알림 표시기가 사용될 경우, `clicked` 이벤트는 무시됩니다.
이러한 이유로 만약 Tray API가 모든 플랫폼에서 똑같이 작동하게 하고 싶다면, 설계시 `clicked` 이벤트에 의존하지 말아야합니다.
그리고 언제나 컨텍스트 메뉴를 포함해서 사용해야 합니다.
## Class: Tray
`Tray`는 [EventEmitter][event-emitter]를 상속 받았습니다.
### new Tray(image)
* `image` [NativeImage](native-image-ko.md)
전달된 `image`를 이용하여 트레이 아이콘을 만듭니다.
### Event: 'clicked'
* `event` Event
* `altKey` Boolean
* `shiftKey` Boolean
* `ctrlKey` Boolean
* `metaKey` Boolean
* `bounds` Object - 트레이 아이콘의 범위
* `x` Integer
* `y` Integer
* `width` Integer
* `height` Integer
트레이 아이콘이 클릭될 때 발생하는 이벤트입니다.
__주의:__ `bounds`는 OS X 와 Windows 7 이후 버전에서만 작동합니다.
### Event: 'right-clicked'
* `event` Event
* `altKey` Boolean
* `shiftKey` Boolean
* `ctrlKey` Boolean
* `metaKey` Boolean
* `bounds` Object - 트레이 아이콘의 범위
* `x` Integer
* `y` Integer
* `width` Integer
* `height` Integer
트레이 아이콘을 오른쪽 클릭될 때 호출 됩니다.
__주의:__ 이 기능은 OS X 와 Windows 운영체제에서만 작동합니다.
### Event: 'double-clicked'
* `event` Event
* `altKey` Boolean
* `shiftKey` Boolean
* `ctrlKey` Boolean
* `metaKey` Boolean
* `bounds` Object - 트레이 아이콘의 범위
* `x` Integer
* `y` Integer
* `width` Integer
* `height` Integer
트레이 아이콘이 더블 클릭될 때 발생하는 이벤트입니다.
__주의:__ 이 기능은 OS X 와 Windows 운영체제에서만 작동합니다.
### Event: 'balloon-show'
알림풍선이 보여질 때 발생하는 이벤트입니다.
__주의:__ 이 기능은 Windows에서만 작동합니다.
### Event: 'balloon-clicked'
알림풍선이 클릭될 때 발생하는 이벤트입니다.
__주의:__ 이 기능은 Windows에서만 작동합니다.
### Event: 'balloon-closed'
알림풍선이 시간이 지나 사라지거나 유저가 클릭하여 닫을 때 발생하는 이벤트입니다.
__주의:__ 이 기능은 Windows에서만 작동합니다.
### Event: 'drop-files'
* `event`
* `files` Array - 드롭된 파일의 경로
트레이 아이콘에 파일이 드롭되면 발생하는 이벤트입니다.
__주의:__ 이 기능은 OS X에서만 작동합니다.
### Tray.destroy()
트레이 아이콘을 즉시 삭제시킵니다.
### Tray.setImage(image)
* `image` [NativeImage](native-image-ko.md)
`image`를 사용하여 트레이 아이콘의 이미지를 설정합니다.
### Tray.setPressedImage(image)
* `image` [NativeImage](native-image-ko.md)
`image`를 사용하여 트레이 아이콘이 눌렸을 때의 이미지를 설정합니다.
__주의:__ 이 기능은 OS X에서만 작동합니다.
### Tray.setToolTip(toolTip)
* `toolTip` String
트레이 아이콘의 툴팁 텍스트를 설정합니다.
### Tray.setTitle(title)
* `title` String
상태바에서 트레이 아이콘 옆에 표시되는 제목 텍스트를 설정합니다.
__주의:__ 이 기능은 OS X에서만 작동합니다.
### Tray.setHighlightMode(highlight)
* `highlight` Boolean
트레이 아이콘을 클릭했을 때 하이라이트 될지 설정합니다.
__주의:__ 이 기능은 OS X에서만 작동합니다.
### Tray.displayBalloon(options)
* `options` Object
* `icon` [NativeImage](native-image-ko.md)
* `title` String
* `content` String
트레이에 알림풍선을 생성합니다.
__알림:__ 이 기능은 Windows에서만 작동합니다.
### Tray.popContextMenu([position])
* `position` Object - 팝 메뉴 위치
* `x` Integer
* `y` Integer
`position`은 Windows에서만 사용할 수 있으며 기본값은 (0, 0)입니다.
__주의:__ 이 기능은 Windows 와 OS X에서만 작동합니다.
### Tray.setContextMenu(menu)
* `menu` Menu
트레이에 컨텍스트 메뉴를 설정합니다.
[event-emitter]: http://nodejs.org/api/events.html#events_class_events_eventemitter

View file

@ -1,67 +0,0 @@
# web-frame
`web-frame` 모듈은 현재 웹 페이지의 랜더링 상태를 설정 할 수 있도록 해줍니다.
다음 예제는 현재 페이지를 200% 줌 합니다.
```javascript
var webFrame = require('web-frame');
webFrame.setZoomFactor(2);
```
## webFrame.setZoomFactor(factor)
* `factor` Number - Zoom 값
지정한 값으로 페이지를 줌 합니다. 줌 값은 퍼센트 / 100입니다. (예시: 300% = 3.0)
## webFrame.getZoomFactor()
현재 줌 값을 반환합니다.
## webFrame.setZoomLevel(level)
* `level` Number - Zoom level
지정한 레벨로 줌 레벨을 변경합니다. 0은 "기본 크기" 입니다.
그리고 각각 레벨 값을 올리거나 내릴 때마다 20%씩 커지거나 작아지고 기본 크기의 50%부터 300%까지 조절 제한이 있습니다.
## webFrame.getZoomLevel()
현재 줌 레벨을 반환합니다.
## webFrame.setSpellCheckProvider(language, autoCorrectWord, provider)
* `language` String
* `autoCorrectWord` Boolean
* `provider` Object
Input field나 text area에 철자 검사(spell checking) 제공자를 설정합니다.
`provider`는 반드시 전달된 단어의 철자가 맞았는지 검사하는 `spellCheck` 메소드를 가지고 있어야 합니다.
[node-spellchecker][spellchecker]를 철자 검사 제공자로 사용하는 예제입니다:
```javascript
require('web-frame').setSpellCheckProvider("en-US", true, {
spellCheck: function(text) {
return !(require('spellchecker').isMisspelled(text));
}
});
```
## webFrame.registerUrlSchemeAsSecure(scheme)
* `scheme` String
지정한 `scheme`을 보안 스킴으로 등록합니다.
보안 스킴은 혼합된 컨텐츠 경고를 발생시키지 않습니다. 예를 들어 `https``data`는 네트워크 공격자로부터 손상될 가능성이 없기 때문에 보안 스킴이라고 할 수 있습니다.
## webFrame.registerUrlSchemeAsBypassingCsp(scheme)
* `scheme` String
페이지 컨텐츠의 보안 정책에 상관없이 이 `scheme`로부터 리소스가 로드됩니다.
[spellchecker]: https://github.com/atom/node-spellchecker

View file

@ -1,487 +0,0 @@
# `<webview>` 태그
`guest` 컨텐츠(웹 페이지)를 Electron 앱 페이지에 삽입하기 위해 `webview` 태그를 사용할 수 있습니다.
게스트 컨텐츠는 `webview` 컨테이너에 담겨 대상 페이지에 삽입되고 해당 페이지에선 게스트 컨텐츠의 배치 및 렌더링 과정을 조작할 수 있습니다.
`iframe``webview`의 차이는 어플리케이션과 프로세스가 분리되어 돌아간다는 점입니다.
그것은 모든 권한이 웹 페이지와 같지 않고 모든 앱과 임베디드(게스트) 컨텐츠간의 상호작용이 비동기로 작동한다는 것을 의미합니다.
이에 따라 임베디드 컨텐츠로부터 어플리케이션을 안전하게 유지할 수 있습니다.
## 예제
웹 페이지를 어플리케이션에 삽입하려면 `webview` 태그를 사용해 원하는 타겟 페이지에 추가하면 됩니다. (게스트 컨텐츠가 앱 페이지에 추가 됩니다)
간단한 예로 `webview` 태그의 `src` 속성에 페이지를 지정하고 css 스타일을 이용해서 컨테이너의 외관을 설정할 수 있습니다:
```html
<webview id="foo" src="https://www.github.com/" style="display:inline-block; width:640px; height:480px"></webview>
```
게스트 컨텐츠를 조작하기 위해 자바스크립트로 `webview` 태그의 이벤트를 리스닝 하여 응답을 받을 수 있습니다.
다음 예제를 참고하세요: 첫번째 리스너는 페이지 로딩 시작시의 이벤트를 확인하고 두번째 리스너는 페이지의 로딩이 끝난시점을 확인합니다.
그리고 페이지를 로드하는 동안 "loading..." 메시지를 표시합니다.
```html
<script>
onload = function() {
var webview = document.getElementById("foo");
var indicator = document.querySelector(".indicator");
var loadstart = function() {
indicator.innerText = "loading...";
}
var loadstop = function() {
indicator.innerText = "";
}
webview.addEventListener("did-start-loading", loadstart);
webview.addEventListener("did-stop-loading", loadstop);
}
</script>
```
## 태그 속성
### src
```html
<webview src="https://www.github.com/"></webview>
```
지정한 URL을 페이지 소스로 사용합니다. 이 속성을 지정할 경우 `webview`의 최상위 페이지가 됩니다.
`src`에 같은 페이지를 지정하면 페이지를 새로고침합니다.
`src` 속성은 `data:text/plain,Hello, world!` 같은 data URL도 사용할 수 있습니다.
### autosize
```html
<webview src="https://www.github.com/" autosize="on" minwidth="576" minheight="432"></webview>
```
"on" 으로 지정하면 `webview` 컨테이너는 `minwidth`, `minheight`, `maxwidth`, `maxheight`에 맞춰서 자동으로 크기를 조절합니다.
이 조건은 `autosize`가 활성화되어있지 않는 한 따로 영향을 주지 않습니다.
`autosize`가 활성화 되어있으면 `webview` 컨테이너의 크기는 각각의 지정한 최대, 최소값에 따라 조절됩니다.
### nodeintegration
```html
<webview src="http://www.google.com/" nodeintegration></webview>
```
"on"으로 지정하면 `webview` 페이지 내에서 `require``process 객체`같은 node.js API를 사용할 수 있습니다.
이를 지정하면 내부에서 로우레벨 리소스에 접근할 수 있습니다.
### plugins
```html
<webview src="https://www.github.com/" plugins></webview>
```
"on"으로 지정하면 `webview` 내부에서 브라우저 플러그인을 사용할 수 있습니다.
### preload
```html
<webview src="https://www.github.com/" preload="./test.js"></webview>
```
게스트 페이지가 로드되기 전에 실행할 스크립트를 지정합니다.
스크립트 URL은 `file:` 또는 `asar:` 프로토콜 중 하나를 반드시 사용해야 합니다.
왜냐하면 `require`를 사용해 게스트 페이지 내에서 스크립트를 로드하기 때문입니다.
게스트 페이지가 nodeintegration을 활성화 하지 않았어도 지정된 스크립트는 정상적으로 돌아갑니다.
하지만 스크립트 내에서 사용할 수 있는 global 객체는 스크립트 작동이 끝나면 삭제됩니다.
### httpreferrer
```html
<webview src="https://www.github.com/" httpreferrer="http://cheng.guru"></webview>
```
게스트 페이지의 referrer URL을 설정합니다.
### useragent
```html
<webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview>
```
게스트 페이지의 `User-Agent`를 설정합니다. 페이지가 로드된 후엔 `setUserAgent` 메소드를 사용해서 변경할 수 있습니다.
### disablewebsecurity
```html
<webview src="https://www.github.com/" disablewebsecurity></webview>
```
"on"으로 지정하면 게스트 페이지의 웹 보안을 해제합니다.
## API
webview 메서드는 페이지 로드가 끝난 뒤에만 사용할 수 있습니다.
**예제**
```javascript
webview.addEventListener("dom-ready", function() {
webview.openDevTools();
});
```
### `<webview>`.getUrl()
게스트 페이지의 URL을 반환합니다.
### `<webview>`.getTitle()
게스트 페이지의 제목을 반환합니다.
### `<webview>`.isLoading()
페이지가 아직 리소스를 로딩하고 있는지 확인합니다.
### `<webview>`.isWaitingForResponse()
게스트 페이지가 메인 리소스의 첫 응답을 기다리고 있는지 확인합니다.
### `<webview>`.stop()
모든 탐색을 취소합니다.
### `<webview>`.reload()
페이지를 새로고침합니다.
### `<webview>`.reloadIgnoringCache()
캐시를 무시하고 페이지를 새로고침합니다.
### `<webview>`.canGoBack()
페이지 히스토리를 한 칸 뒤로 가기를 할 수 있는지 확인합니다.
### `<webview>`.canGoForward()
페이지 히스토리를 한 칸 앞으로 가기를 할 수 있는지 확인합니다.
### `<webview>`.canGoToOffset(offset)
* `offset` Integer
페이지 히스토리를 `offset` 만큼 이동할 수 있는지 확인합니다.
### `<webview>`.clearHistory()
탐색 히스토리를 비웁니다.
### `<webview>`.goBack()
페이지 뒤로 가기를 실행합니다.
### `<webview>`.goForward()
페이지 앞으로 가기를 실행합니다.
### `<webview>`.goToIndex(index)
* `index` Integer
페이지를 지정한 `index`로 이동합니다.
### `<webview>`.goToOffset(offset)
* `offset` Integer
현재 페이지로 부터 `offset` 만큼 이동합니다.
### `<webview>`.isCrashed()
랜더러 프로세스가 크래시 됬는지 확인합니다.
### `<webview>`.setUserAgent(userAgent)
* `userAgent` String
`User-Agent`를 지정합니다.
### `<webview>`.getUserAgent()
현재 페이지의 `User-Agent` 문자열을 가져옵니다.
### `<webview>`.insertCSS(css)
* `css` String
게스트 페이지에 CSS를 삽입합니다.
### `<webview>`.executeJavaScript(code[, userGesture])
* `code` String
* `userGesture` Boolean
게스트 페이지에서 자바스크립트 `code`를 실행합니다.
`userGesture``true`로 설정되어 있으면 `requestFullScreen` HTML API 같이
유저의 승인이 필요한 API를 유저의 승인을 무시하고 개발자가 API를 직접 사용할 수 있습니다.
역주: 기본적으로 브라우저에선 전체화면, 웹캠, 파일 열기등의 API를 사용하려면 유저의 승인(이벤트)이 필요합니다.
### `<webview>`.openDevTools()
게스트 페이지에 대한 개발자 툴을 엽니다.
### `<webview>`.closeDevTools()
게스트 페이지에 대한 개발자 툴을 닫습니다.
### `<webview>`.isDevToolsOpened()
게스트 페이지에 대한 개발자 툴이 열려있는지 확인합니다.
### `<webview>`.inspectElement(x, y)
* `x` Integer
* `y` Integer
(`x`, `y`) 위치에 있는 엘리먼트를 inspect합니다.
### `<webview>`.inspectServiceWorker()
Service worker에 대한 개발자 툴을 엽니다.
### `<webview>`.undo()
페이지에서 실행 취소 커맨드를 실행합니다.
### `<webview>`.redo()
페이지에서 다시 실행 커맨드를 실행합니다.
### `<webview>`.cut()
페이지에서 잘라내기 커맨드를 실행합니다.
### `<webview>`.copy()
페이지에서 복사 커맨드를 실행합니다.
### `<webview>`.paste()
페이지에서 붙여넣기 커맨드를 실행합니다.
### `<webview>`.pasteAndMatchStyle()
페이지에서 `pasteAndMatchStyle` 편집 커맨드를 실행합니다.
### `<webview>`.delete()
페이지에서 삭제 커맨드를 실행합니다.
### `<webview>`.selectAll()
페이지에서 전체 선택 커맨드를 실행합니다.
### `<webview>`.unselect()
페이지에서 `unselect` 커맨드를 실행합니다.
### `<webview>`.replace(text)
* `text` String
페이지에서 `replace` 커맨드를 실행합니다.
### `<webview>`.replaceMisspelling(text)
* `text` String
페이지에서 `replaceMisspelling` 커맨드를 실행합니다.
### `<webview>`.print([options])
Webview 페이지를 인쇄합니다. `webContents.print([options])` 메서드와 같습니다.
### `<webview>`.printToPDF(options, callback)
Webview 페이지를 PDF 형식으로 인쇄합니다. `webContents.printToPDF(options, callback)` 메서드와 같습니다.
### `<webview>`.send(channel[, args...])
* `channel` String
`channel`을 통해 게스트 페이지에 `args...` 비동기 메시지를 보냅니다.
게스트 페이지에선 `ipc` 모듈의 `channel` 이벤트를 사용하면 이 메시지를 받을 수 있습니다.
예제는 [WebContents.send](browser-window-ko.md#webcontentssendchannel-args)를 참고하세요.
## DOM 이벤트
### load-commit
* `url` String
* `isMainFrame` Boolean
Fired when a load has committed. This includes navigation within the current
document as well as subframe document-level loads, but does not include
asynchronous resource loads.
### did-finish-load
탐색이 끝나면 발생하는 이벤트입니다. 브라우저 탭의 스피너가 멈추고 `onload` 이벤트가 발생될 때를 생각하면 됩니다.
### did-fail-load
* `errorCode` Integer
* `errorDescription` String
`did-finish-load`와 비슷합니다. 하지만 이 이벤트는 `window.stop()`과 같은 무언가로 인해 로드에 실패했을 때 발생하는 이벤트입니다.
### did-frame-finish-load
* `isMainFrame` Boolean
프레임의 탐색이 끝나면 발생하는 이벤트입니다.
### did-start-loading
브라우저 탭의 스피너가 돌기 시작할 때 처럼 페이지의 로드가 시작될 때 발생하는 이벤트입니다.
### did-stop-loading
브라우저 탭의 스피너가 멈출 때 처럼 페이지의 로드가 끝나면 발생하는 이벤트입니다.
### did-get-response-details
* `status` Boolean
* `newUrl` String
* `originalUrl` String
* `httpResponseCode` Integer
* `requestMethod` String
* `referrer` String
* `headers` Object
요청한 리소스에 관해 자세한 내용을 알 수 있을 때 발생하는 이벤트입니다.
`status`는 리소스를 다운로드할 소켓 커낵션을 나타냅니다.
### did-get-redirect-request
* `oldUrl` String
* `newUrl` String
* `isMainFrame` Boolean
리소스를 요청하고 받는 도중에 리다이렉트가 생기면 발생하는 이벤트입니다.
### dom-ready
현재 프레임 문서의 로드가 끝나면 발생하는 이벤트입니다.
### page-title-set
* `title` String
* `explicitSet` Boolean
탐색하는 동안에 페이지의 제목이 설정되면 발생하는 이벤트입니다. `explicitSet`는 파일 URL에서 종합(synthesised)된 제목인 경우 false로 표시됩니다.
### page-favicon-updated
* `favicons` Array - Array of Urls
페이지가 favicon URL을 받았을 때 발생하는 이벤트입니다.
### enter-html-full-screen
페이지가 HTML API에 의해 전체 화면 모드에 돌입했을 때 발생하는 이벤트입니다.
### leave-html-full-screen
페이지의 전체 화면 모드가 해제됬을 때 발생하는 이벤트입니다.
### console-message
* `level` Integer
* `message` String
* `line` Integer
* `sourceId` String
`console.log` API에 의해 로깅될 때 발생하는 이벤트입니다.
다음 예제는 모든 로그 메시지를 로그 레벨이나 다른 속성에 관련 없이 호스트 페이지의 콘솔에 다시 로깅하는 예제입니다.
```javascript
webview.addEventListener('console-message', function(e) {
console.log('Guest page logged a message:', e.message);
});
```
### new-window
* `url` String
* `frameName` String
* `disposition` String - Can be `default`, `foreground-tab`, `background-tab`,
`new-window` and `other`
게스트 페이지가 새로운 브라우저 창을 생성할 때 발생하는 이벤트입니다.
다음 예제 코드는 새 URL을 시스템의 기본 브라우저로 여는 코드입니다.
```javascript
webview.addEventListener('new-window', function(e) {
require('shell').openExternal(e.url);
});
```
### close
게스트 페이지가 자체적으로 닫힐 때 발생하는 이벤트입니다.
다음 예제 코드는 게스트 페이지가 자체적으로 닫힐 때 `webview``about:blank` 페이지로 이동시키는 예제입니다.
```javascript
webview.addEventListener('close', function() {
webview.src = 'about:blank';
});
```
### ipc-message
* `channel` String
* `args` Array
호스트 페이지에서 비동기 IPC 메시지를 보낼 때 발생하는 이벤트입니다.
`sendToHost` 메소드와 `ipc-message` 이벤트로 호스트 페이지와 쉽게 통신을 할 수 있습니다:
```javascript
// In embedder page.
webview.addEventListener('ipc-message', function(event) {
console.log(event.channel);
// Prints "pong"
});
webview.send('ping');
```
```javascript
// In guest page.
var ipc = require('ipc');
ipc.on('ping', function() {
ipc.sendToHost('pong');
});
```
### crashed
랜더러 프로세스가 크래시 되었을 때 발생하는 이벤트입니다.
### gpu-crashed
GPU 프로세스가 크래시 되었을 때 발생하는 이벤트입니다.
### plugin-crashed
* `name` String
* `version` String
플러그인 프로세스가 크래시 되었을 때 발생하는 이벤트입니다.
### destroyed
WebContents가 파괴될 때 발생하는 이벤트입니다.

View file

@ -1,57 +0,0 @@
# `window.open` 함수
`window.open` 함수가 호출되면 새 창에서 새로운 페이지를 불러옵니다.
이 창은 `url`로 부터 만들어진 `BrowserWindow`의 새 인스턴스이며 본 객체 대신 페이지의 컨트롤이 제한된 프록시 객체를 반환합니다.
프록시 객체는 기존의 웹 페이지와 호환될 수 있도록 일부 제한된 표준 기능만 가지고 있습니다.
창의 모든 컨트롤을 가지려면 `BrowserWindow`를 직접 생성하여 작업해야 합니다.
## window.open(url, [frameName[, features]])
* `url` String
* `frameName` String
* `features` String
`BrowserWindowProxy` 클래스의 객체를 반환하는 새로운 윈도우를 생성합니다.
## window.opener.postMessage(message, targetOrigin)
* `message` String
* `targetOrigin` String
부모 윈도우에 메시지를 보냅니다. 특정한 origin을 지정할 수도 있으며 `*`를 지정하면 따로 origin 설정을 사용하지 않습니다.
## Class: BrowserWindowProxy
### BrowserWindowProxy.blur()
자식 윈도우의 포커스를 해제합니다.
### BrowserWindowProxy.close()
자식 윈도우를 강제로 닫습니다. unload 이벤트가 발생하지 않습니다.
Forcefully closes the child window without calling its unload event.
### BrowserWindowProxy.closed
자식 윈도우가 닫히면 true로 설정됩니다.
### BrowserWindowProxy.eval(code)
* `code` String
자식 윈도우에서 특정 스크립트를 실행합니다.
### BrowserWindowProxy.focus()
자식 윈도우에 포커스를 맞춥니다. (창을 맨 앞으로 가져옵니다)
### BrowserWindowProxy.postMessage(message, targetOrigin)
* `message` String
* `targetOrigin` String
자식 윈도우에 메시지를 보냅니다. 특정한 origin을 지정할 수도 있으며 `*`를 지정하면 따로 origin 설정을 사용하지 않습니다.
참고로 자식 윈도우의 `window.opener` 객체에는 다른 속성 없이 이 함수 하나만 구현되어 있습니다.

View file

@ -1,34 +0,0 @@
# NW.js와 기술적으로 다른점 (이전 node-webkit)
__알림: Electron은 이전까지 Atom Shell로 불려졌습니다.__
NW.js 처럼 Electron은 JavaScript와 HTML 그리고 Node 통합환경을 제공함으로써 웹 페이지에서 저수준 시스템에 접근할 수 있는 웹 기반 데스크탑 어플리케이션을 작성할 수 있도록 합니다.
하지만 Electron과 NW.js는 근본적인 개발흐름의 차이도 있습니다:
__1. 어플리케이션의 엔트리 포인트__
NW.js에선 어플리케이션의 엔트리 포인트로 웹 페이지를 사용합니다.
`package.json`내의 main 필드에 메인 웹 페이지(index.html) 파일을 지정하면 어플리케이션의 메인 윈도우로 열리게 됩니다.
Electron에선 JavaScript를 엔트리 포인트로 사용합니다. URL을 직접 제공하는 대신 API를 사용하여 직접 브라우저 창과 HTML 파일을 로드할 수 있습니다.
또한 윈도우의 종료시기를 결정하는 이벤트를 리스닝해야합니다.
Electron은 Node.js 런타임과 비슷하게 작동합니다. Electron의 API는 저수준이기에 브라우저 테스팅을 위해 [PhantomJS](http://phantomjs.org/)를 사용할 수도 있습니다.
__2. 빌드 시스템__
Electron은 Chromium의 모든것을 빌드하는 복잡성을 피하기 위해 [libchromiumcontent](https://github.com/brightray/libchromiumcontent)를 사용하여
Chromium의 Content API에 접근합니다. libchromiumcontent은 단일 공유 라이브러리이고 Chromium Content 모듈과 종속성 라이브러리들을 포함합니다.
유저는 Electron을 빌드 하기 위해 높은 사양의 빌드용 컴퓨터를 구비할 필요가 없습니다.
__3. Node 통합__
NW.js는 웹 페이지에서 require를 사용할 수 있도록 Chromium을 패치했습니다. 한편 Electron은 Chromium의 해킹을 방지하기 위해 libuv loop와 각 플랫폼의 메시지 루프에 통합하는 등의 다른 방법을 채택하였습니다.
[`node_bindings`](../../atom/common/) 코드를 보면 이 부분이 어떻게 구현됬는지를 알 수 있습니다.
__4. 다중 컨텍스트__
만약 NW.js를 사용해본적이 있다면 Node context와 Web context의 개념을 잘 알고 있을겁니다. 이 개념은 NW.js가 구현된 방식에 따라 만들어졌습니다.
Node의 [다중 컨텍스트](http://strongloop.com/strongblog/whats-new-node-js-v0-12-multiple-context-execution/)를 사용할 경우 Electron은 웹 페이지에서 새로운 JavaScript 컨텍스트를 생성하지 않습니다.

View file

@ -1,122 +0,0 @@
# 빌드 설명서 (Linux)
## 빌드전 요구사양
* Python 2.7.x. 몇몇 CentOS와 같은 배포판들은 아직도 Python 2.6.x 버전을 사용합니다. 그래서 `python -V`를 통해 버전을 확인해 줄 필요가 있습니다.
* Node.js v0.12.x. Node를 설치하는 방법은 여러가지가 있습니다. 그중 하나는 [Node.js](http://nodejs.org) 사이트에서 소스코드를 받아 빌드하는 방법입니다.
이렇게 하면 Node를 일반 유저로 홈 디렉터리에 설치할 수 있습니다. 또는 [NodeSource](https://nodesource.com/blog/nodejs-v012-iojs-and-the-nodesource-linux-repositories) 에서 받아올 수도 있습니다.
자세한 내용은 [Node.js 설치 방법](https://github.com/joyent/node/wiki/Installation) 을 참고하세요.
* Clang 3.4 또는 최신 버전
* GTK+ 와 libnotify의 개발용 헤더
Ubuntu를 사용하고 있다면 다음 커맨드로 설치하면 합니다:
```bash
$ sudo apt-get install build-essential clang libdbus-1-dev libgtk2.0-dev \
libnotify-dev libgnome-keyring-dev libgconf2-dev \
libasound2-dev libcap-dev libcups2-dev libxtst-dev \
libxss1 libnss3-dev gcc-multilib g++-multilib
```
다른 배포판의 경우 yum과 같은 패키지 매니저를 통해 패키지를 설치 할 수 있습니다. 패키지의 이름은 대부분 비슷할 것입니다.
또는 소스코드를 내려받아 직접 빌드하는 방법도 있습니다.
## 가상머신을 사용하여 빌드 하는 경우
만약 Electron을 가상머신으로 빌드 할 계획이라면 해당 가상머신의 스토리지를 최소 25GB 이상을 확보해 놓아야 합니다.
## 코드 가져오기
```bash
$ git clone https://github.com/atom/electron.git
```
## 부트 스트랩
부트스트랩 스크립트는 필수적인 빌드 종속성 라이브러리들을 모두 다운로드하고 프로젝트 파일을 생성합니다.
스크립트가 정상적으로 작동하기 위해선 Python 2.7.x 버전이 필요합니다.
아마 다운로드 작업이 상당히 많은 시간을 소요할 것입니다.
참고로 Electron은 빌드 툴체인으로 `ninja`를 사용하므로 `Makefile`은 생성되지 않습니다.
```bash
$ cd electron
$ ./script/bootstrap.py -v
```
### 크로스 컴파일
`arm` 아키텍쳐로 빌드 하려면 먼저 종속성 라이브러리를 설치해야 합니다:
```bash
$ sudo apt-get install libc6-dev-armhf-cross linux-libc-dev-armhf-cross \
g++-arm-linux-gnueabihf
```
그리고 `bootstrap.py` 스크립트의 `--target_arch` 파라미터에 `arm` 또는 `ia32` 아키텍쳐를 지정하여 크로스 컴파일 할 수 있습니다:
```bash
$ ./script/bootstrap.py -v --target_arch=arm
```
## 빌드 하기
`Release``Debug` 두 타겟 모두 빌드 합니다:
```bash
$ ./script/build.py
```
이 스크립트는 `out/R` 디렉터리에 크기가 매우 큰 Electron 실행 파일을 배치합니다. 파일 크기는 1.3GB를 초과합니다.
이러한 문제가 발생하는 이유는 Release 타겟 바이너리가 디버그 심볼을 포함하기 때문입니다.
파일 크기를 줄이려면 `create-dist.py` 스크립트를 실행하세요:
```bash
$ ./script/create-dist.py
```
이 스크립트는 매우 작은 배포판을 `dist` 디렉터리에 생성합니다.
create-dist.py 스크립트를 실행한 이후 1.3GB를 초과하는 공간을 차지하는 out/R 폴더의 실행파일 바이너리는 삭제해도 됩니다.
`Debug` 타겟만 빌드 할 수도 있습니다:
```bash
$ ./script/build.py -c D
```
빌드가 모두 끝나면 `out/D` 디렉터리에서 `electron` 디버그 바이너리를 찾을 수 있습니다.
## 정리 하기
빌드 파일들을 정리합니다:
```bash
$ ./script/clean.py
```
## 문제 해결
개발 종속성 라이브러리들을 제대로 설치했는지 확인하세요.
## libtinfo.so.5 동적 링크 라이브러리를 로드하는 도중 에러가 발생할 경우
미리 빌드된 `clang``libtinfo.so.5`로 링크를 시도합니다.
플랫폼에 따라 적당한 `libncurses` symlink를 추가하세요.
```bash
$ sudo ln -s /usr/lib/libncurses.so.5 /usr/lib/libtinfo.so.5
```
## 테스트
프로젝트 코딩 스타일을 확인하려면:
```bash
$ ./script/cpplint.py
```
테스트를 실행하려면:
```bash
$ ./script/test.py
```

View file

@ -1,61 +0,0 @@
# 빌드 설명서 (Mac)
## 빌드전 요구 사항
* OS X >= 10.8
* [Xcode](https://developer.apple.com/technologies/tools/) >= 5.1
* [node.js](http://nodejs.org) (external).
만약 Homebrew를 이용해 파이선을 설치했다면 다음 파이선 모듈도 같이 설치해야 합니다:
* pyobjc
## 코드 가져오기
```bash
$ git clone https://github.com/atom/electron.git
```
## 부트 스트랩
부트스트랩 스크립트는 필수적인 빌드 종속성 라이브러리들을 모두 다운로드하고 프로젝트 파일을 생성합니다.
참고로 Electron은 빌드 툴체인으로 `ninja`를 사용하므로 Xcode 프로젝트는 생성되지 않습니다.
```bash
$ cd electron
$ ./script/bootstrap.py -v
```
## 빌드 하기
`Release``Debug` 두 타겟 모두 빌드 합니다:
```bash
$ ./script/build.py
```
`Debug` 타겟만 빌드 할 수도 있습니다:
```bash
$ ./script/build.py -c D
```
빌드가 모두 끝나면 `out/D` 디렉터리에서 `Electron.app` 실행 파일을 찾을 수 있습니다.
## 32비트 지원
Electron은 현재 OS X 64비트 빌드만 지원하고 있습니다. 그리고 앞으로도 OS X 32비트는 지원할 계획이 없습니다.
## 테스트
프로젝트 코딩 스타일을 확인하려면:
```bash
$ ./script/cpplint.py
```
테스트를 실행하려면:
```bash
$ ./script/test.py
```

View file

@ -1,125 +0,0 @@
# 빌드 설명서 (Windows)
## 빌드전 요구 사항
* Windows 7 / Server 2008 R2 또는 최신 버전
* Visual Studio 2013 - [VS 2013 커뮤니티 에디션 무료 다운로드](http://www.visualstudio.com/products/visual-studio-community-vs)
* [Python 2.7](http://www.python.org/download/releases/2.7/)
* [Node.js](http://nodejs.org/download/)
* [git](http://git-scm.com)
현재 Windows를 설치하지 않았다면 [modern.ie](https://www.modern.ie/en-us/virtualization-tools#downloads)에서
사용기한이 정해져있는 무료 가상머신 버전의 Windows를 받아 Electron을 빌드할 수도 있습니다.
Electron은 전적으로 command-line 스크립트를 사용하여 빌드합니다. 그렇기에 Electron을 개발하는데 아무런 에디터나 사용할 수 있습니다.
하지만 이 말은 Visual Studio를 개발을 위해 사용할 수 없다는 말이 됩니다. 나중에 Visual Studio를 이용한 빌드 방법도 제공할 예정입니다.
**참고:** Visual Studio가 빌드에 사용되지 않더라도 제공된 빌드 툴체인이 **필수적으로** 사용되므로 여전히 필요합니다.
## 코드 가져오기
```powershell
git clone https://github.com/atom/electron.git
```
## 부트 스트랩
부트스트랩 스크립트는 필수적인 빌드 종속성 라이브러리들을 모두 다운로드하고 프로젝트 파일을 생성합니다.
참고로 Electron은 빌드 툴체인으로 `ninja`를 사용하므로 Visual Studio 프로젝트는 생성되지 않습니다.
```powershell
cd electron
python script\bootstrap.py -v
```
## 빌드 하기
`Release``Debug` 두 타겟 모두 빌드 합니다:
```powershell
python script\build.py
```
`Debug` 타겟만 빌드 할 수도 있습니다:
```powershell
python script\build.py -c D
```
빌드가 모두 끝나면 `out/D` 디렉터리에서 `atom.exe` 실행 파일을 찾을 수 있습니다.
## 64비트 빌드
64비트를 타겟으로 빌드 하려면 부트스트랩 스크립트를 실행할 때 `--target_arch=x64` 인자를 같이 넘겨주면 됩니다:
```powershell
python script\bootstrap.py -v --target_arch=x64
```
다른 빌드 단계도 정확하게 같습니다.
## 테스트
프로젝트 코딩 스타일을 확인하려면:
```powershell
python script\cpplint.py
```
테스트를 실행하려면:
```powershell
python script\test.py
```
## 문제 해결
### Command xxxx not found
만약 `Command xxxx not found`와 같은 형식의 에러가 발생했다면 `VS2012 Command Prompt` 콘솔로 빌드 스크립트를 실행해볼 필요가 있습니다.
### Fatal internal compiler error: C1001
Visual Studio가 업데이트까지 완벽하게 설치된 최신버전인지 확인하세요.
### Assertion failed: ((handle))->activecnt >= 0
Cygwin에서 빌드 할 경우 `bootstrap.py` 스크립트가 다음의 에러와 함께 빌드에 실패할 수 있습니다:
```
Assertion failed: ((handle))->activecnt >= 0, file src\win\pipe.c, line 1430
Traceback (most recent call last):
File "script/bootstrap.py", line 87, in <module>
sys.exit(main())
File "script/bootstrap.py", line 22, in main
update_node_modules('.')
File "script/bootstrap.py", line 56, in update_node_modules
execute([NPM, 'install'])
File "/home/zcbenz/codes/raven/script/lib/util.py", line 118, in execute
raise e
subprocess.CalledProcessError: Command '['npm.cmd', 'install']' returned non-zero exit status 3
```
이 버그는 Cygwin python과 Win32 node를 같이 사용할 때 발생합니다.
부트스트랩 스크립트에서 Win32 python을 사용함으로써 이 문제를 해결할 수 있습니다 (`C:\Python27` 디렉터리에 python이 설치되었다는 것을 가정하면):
```bash
/cygdrive/c/Python27/python.exe script/bootstrap.py
```
### LNK1181: cannot open input file 'kernel32.lib'
32bit node.js를 다시 설치하세요.
### Error: ENOENT, stat 'C:\Users\USERNAME\AppData\Roaming\npm'
간단하게 해당 디렉터리를 생성하면 [문제가 해결될 겁니다](http://stackoverflow.com/a/25095327/102704):
```powershell
mkdir ~\AppData\Roaming\npm
```
### node-gyp is not recognized as an internal or external command
Git Bash로 빌드 했을 때 이러한 에러가 발생할 수 있습니다. 반드시 PowerShell이나 VS2012 Command Prompt에서 빌드를 진행해야 합니다.

View file

@ -1,56 +0,0 @@
# 빌드 시스템 개요
Electron은 프로젝트 생성을 위해 `gyp`를 사용하며 `ninja`를 이용하여 빌드합니다.
프로젝트 설정은 `.gyp``.gypi` 파일에서 볼 수 있습니다.
## gyp 파일들
Electron을 빌드 할 때 `gyp` 파일들은 다음과 같은 규칙을 따릅니다:
* `atom.gyp`는 Electron의 빌드 과정 자체를 정의합니다.
* `common.gypi`는 Node가 Chromium과 함께 빌드될 수 있도록 조정한 빌드 설정입니다.
* `vendor/brightray/brightray.gyp``brightray`의 빌드 과정을 정의하고 Chromium과의 링킹에 대한 기본적인 설정을 포함합니다.
* `vendor/brightray/brightray.gypi`는 빌드에 대한 일반적인 설정이 포함되어 있습니다.
## 구성요소 빌드
Chromium은 꽤나 큰 프로젝트입니다. 이 때문에 최종 링킹 작업은 상당한 시간이 소요될 수 있습니다.
이러한 문제로 인해 개발 시 빌드 작업을 까다롭게 만듭니다. 이 문제를 해결하기 위해 Chromium은 "component build"를 도입했습니다.
이는 각각의 컴포넌트를 각각 따로 분리하여 공유 라이브러리로 빌드 합니다. 이렇게 되면 링킹작업은 매우 빨라지지만 파일 크기와 성능이 느려집니다.
Electron도 상당히 비슷한 접근을 했습니다:
`Debug`빌드 시 바이너리는 공유 라이브러리 버전의 Chromium 컴포넌트를 사용해서 링크 속도를 높이고
`Release`빌드 시엔 정적 라이브러리 버전의 컴포넌트를 사용합니다.
이렇게 각 빌드의 단점을 상호 보완하여 디버그 시 빌드 속도는 향상되고 배포판 빌드 시 공유 라이브러리의 단점은 제거했습니다.
## 부트스트랩 최소화
Prebuilt된 모든 Chromium 바이너리들은 부트스트랩 스크립트가 실행될 때 다운로드됩니다.
기본적으로 공유 라이브러리와 정적 라이브러리 모두 다운로드되며 최종 전체 파일 크기는 플랫폼에 따라 800MB에서 2GB까지 차지합니다.
기본적으로 libchromiumcontent는 Amazon Web Service를 통해 다운로드 됩니다.
만약 `LIBCHROMIUMCONTENT_MIRROR` 환경 변수가 설정되어 있으면 부트스트랩은 해당 링크를 사용하여 바이너리를 다운로드 합니다.
[libchromiumcontent-qiniu-mirror](https://github.com/hokein/libchromiumcontent-qiniu-mirror)는 libchromiumcontent의 미러입니다.
만약 AWS에 접근할 수 없다면 `export LIBCHROMIUMCONTENT_MIRROR=http://7xk3d2.dl1.z0.glb.clouddn.com/`를 통해 다운로드 할 수 있습니다.
만약 빠르게 Electron의 개발 또는 테스트만 하고 싶다면 `--dev` 플래그를 추가하여 공유 라이브러리만 다운로드할 수 있습니다:
```bash
$ ./script/bootstrap.py --dev
$ ./script/build.py -c D
```
## 프로젝트 생성 (two-phrase)
Electron은 `Release``Debug` 빌드가 서로 다른 라이브러리 링크 방식을 사용합니다.
그러나 `gyp`는 따로 빌드 설정을 분리하여 라이브러리 링크 방식을 정의하는 것을 지원하지 않습니다.
이러한 문제를 해결하기 위해 Electron은 링크 설정을 제어하는 `gyp` 변수 `libchromiumcontent_component`를 사용하고 `gyp`를 실행할 때 단 하나의 타겟만을 생성합니다.
## 타겟 이름
많은 프로젝트에서 타겟 이름을 `Release``Debug`를 사용하는데 반해 Electron은 `R``D`를 대신 사용합니다.
이유는 가끔 알 수 없는 이유(randomly)로 `Release``Debug` 중 하나만 빌드 설정에 정의되어 있을때 `gyp`가 크래시를 일으키는데
전술한 바와 같이 Electron은 한번에 한개의 타겟만을 생성할 수 있기 때문입니다.
이 문제는 개발자에게만 영향을 미칩니다. 만약 단순히 Electron을 rebranding 하기 위해 빌드 한다면 이 문제에 신경 쓸 필요가 없습니다.

View file

@ -1,22 +0,0 @@
# 코딩 스타일
## C++과 Python
C++과 Python스크립트는 Chromium의 [코딩 스타일](http://www.chromium.org/developers/coding-style)을 따릅니다.
파이선 스크립트 `script/cpplint.py`를 사용하여 모든 파일이 해당 코딩스타일에 맞게 코딩 되었는지 확인할 수 있습니다.
파이선의 버전은 2.7을 사용합니다.
## CoffeeScript
CoffeeScript의 경우 GitHub의 [스타일 가이드](https://github.com/styleguide/javascript)를 따릅니다. 동시에 다음 규칙도 따릅니다:
* Google의 코딩 스타일에도 맞추기 위해 파일의 끝에는 **절대** 개행을 삽입해선 안됩니다.
* 파일 이름의 공백은 `_`대신에 `-`을 사용하여야 합니다. 예를 들어 `file_name.coffee`
`file-name.coffee`로 고쳐야합니다. 왜냐하면 [github/atom](https://github.com/github/atom) 에서 사용되는 모듈의 이름은
보통 `module-name`형식이기 때문입니다. 이 규칙은 '.coffee' 파일에만 적용됩니다.
## API 이름
새로운 API를 만들 땐 getter, setter스타일 대신 jQuery의 one-function스타일을 사용해야 합니다. 예를 들어
`.getText()``.setText(text)`대신에 `.text([text])`형식으로 설계하면 됩니다.
포럼에 이 문제에 대한 [논의](https://github.com/atom/electron/issues/46)가 있습니다.

View file

@ -8,6 +8,13 @@ script `script/cpplint.py` to check whether all files confirm.
The python's version we are using now is Python 2.7.
The C++ code uses a lot of Chromium's abstractions and types, so it's
recommended to get acquainted with them. A good place to start is
Chromium's [Important Abstractions and Data Structures]
(https://www.chromium.org/developers/coding-style/important-abstractions-and-data-structures)
document. The document mentions some special types, scoped types (that
automatically release their memory when going out of scope), logging mechanisms etc.
## CoffeeScript
For CoffeeScript, we follow GitHub's [Style

View file

@ -1,44 +0,0 @@
# 디버거에서 디버그 심볼 서버 설정
디버그 심볼은 디버깅 세션을 더 좋게 개선해 줍니다. 디버그 심볼은 실행 파일과 동적 링크 라이브러리에서 함수에 대한 정보를 담고 있으며 명료한 함수 호출 스텍 정보를 제공합니다.
심볼 서버는 유저가 크기가 큰 디버깅용 파일을 필수적으로 다운로드 받지 않고도 디버거가 알맞은 심볼, 바이너리 그리고 소스를 자동적으로 로드할 수 있도록 해줍니다.
서버 사용법은 [Microsoft의 심볼 서버](http://support.microsoft.com/kb/311503)와 비슷합니다. 이 문서를 참조하세요.
참고로 릴리즈된 Electron 빌드는 자체적으로 많은 최적화가 되어 있는 관계로 경우에 따라 디버깅이 쉽지 않을 수 있습니다.
Inlining, tail call 등의 컴파일러 최적화에 의해 디버거가 모든 변수의 컨텐츠를 보여줄 수 없는 경우도 있고 실행 경로가 이상하게 보여질 수 있습니다.
유일한 해결 방법은 최적화되지 않은 로컬 빌드를 하는 것입니다.
공식적인 Electron의 심볼 서버의 URL은 http://54.249.141.255:8086/atom-shell/symbols 입니다.
일단 이 URL에 직접적으로 접근할 수는 없습니다: 디버깅 툴에 심볼의 경로를 추가해야합니다.
아래의 예제를 참고하면 로컬 캐시 디렉터리는 서버로부터 중복되지 않게 PDB를 가져오는데 사용됩니다.
`c:\code\symbols` 캐시 디렉터리를 사용중인 OS에 맞춰 적당한 경로로 변경하세요.
## Windbg에서 심볼 서버 사용하기
Windbg 심볼 경로는 구분자와 *(별) 문자로 설정되어 있습니다.
Electron 심볼 서버만을 사용하려면 심볼 경로의 엔트리를 추가해야 합니다 (__참고:__ `c:\code\symbols` 디렉터리 경로를 PC가 원하는 경로로 수정할 수 있습니다):
```
SRV*c:\code\symbols\*http://54.249.141.255:8086/atom-shell/symbols
```
Windbg 메뉴 또는 `.sympath` 커맨드를 이용하여 환경에 `_NT_SYMBOL_PATH` 문자열을 설정합니다.
만약 Microsoft의 심볼서버로 부터 심볼을 받아오려면 다음과 같이 리스팅을 먼저 해야합니다:
```
SRV*c:\code\symbols\*http://msdl.microsoft.com/download/symbols;SRV*c:\code\symbols\*http://54.249.141.255:8086/atom-shell/symbols
```
## Visual Studio에서 심볼 서버 사용하기
<img src='http://mdn.mozillademos.org/files/733/symbol-server-vc8express-menu.jpg'>
<img src='http://mdn.mozillademos.org/files/2497/2005_options.gif'>
## 문제 해결: Symbols will not load
Windbg에서 다음의 커맨드를 입력하여 왜 심볼이 로드되지 않았는지에 대한 오류 내역을 출력합니다:
```
> !sym noisy
> .reload /f chromiumcontent.dll
```

View file

@ -1,48 +0,0 @@
# 소스 코드 디렉터리 구조
## 개요
Electron의 소스 코드는 몇 개의 파트로 분리되어 있습니다. 우리는 Chromium의 분리 규칙(separation conventions)을 주로 따르고 있습니다.
이미 [Chromium의 멀티 프로세스 아키텍쳐](http://dev.chromium.org/developers/design-documents/multi-process-architecture)에 익숙해져 있다면 소스 코드를 이해하기 쉬울 것입니다.
## 소스 코드 구조
* **atom** - Electron의 소스코드.
* **app** - 시스템 엔트리 코드.
* **browser** - 주 윈도우를 포함한 프론트엔드, UI, 그리고 메인 프로세스에 관련된 것들. 주 랜더러와 웹 페이지 관리관련 코드.
* **lib** - 메인 프로세스 초기화 코드의 자바스크립트 파트.
* **ui** - 크로스 플랫폼에 대응하는 UI 구현.
* **cocoa** - 코코아 특정 소스 코드.
* **gtk** - GTK+ 특정 소스 코드.
* **win** - Windows GUI 특정 소스 코드.
* **default_app** - 어플리케이션이 제공되지 않으면 기본적으로 사용될 페이지.
* **api** - 메인 프로세스 API들의 구현.
* **lib** - API 구현의 자바스크립트 파트.
* **net** - 네트워크 관련 코드.
* **mac** - Mac 특정 Objective-C 소스 코드.
* **resources** - 아이콘들, 플랫폼 종속성 파일들, 기타 등등.
* **renderer** - 렌더러 프로세스에서 작동하는 코드들.
* **lib** - 렌더러 프로세스 초기화 코드의 자바스크립트 파트.
* **api** - 렌더러 프로세스 API들의 구현.
* **lib** - API 구현의 자바스크립트 파트.
* **common** - 메인 프로세스와 렌더러 프로세스에서 공유하는 코드. 유틸리티 함수와 node 메시지 루프를 Chromium의 메시지 루프에 통합시킨 코드가 포함.
* **lib** - 공통 자바스크립트 초기화 코드.
* **api** - 공통 API들의 구현, Electron의 빌트인 모듈 기초 코드들.
* **lib** - API 구현의 자바스크립트 파트.
* **chromium_src** - 복사된 Chromium 소스 코드.
* **docs** - 참조 문서.
* **spec** - 자동화된 테스트.
* **atom.gyp** - Electron의 빌드 규칙.
* **common.gypi** - 컴파일러 설정 및 `node``breakpad` 등의 구성요소를 위한 빌드 규칙.
## 그외 디렉터리 구조
* **script** - 개발목적으로 사용되는 빌드, 패키징, 테스트, 기타등을 실행하는 스크립트.
* **tools** - gyp 파일에서 사용되는 헬퍼 스크립트 `script`와는 다르게 유저로부터 직접 실행되지 않는 스크립트들을 이곳에 넣습니다.
* **vendor** - 소스코드의 서드파티 종속성 코드 소스 코드 디렉터리가 겹쳐 혼란을 일으킬 수 있기 때문에
우리는 `third_party`와 같은 Chromium 소스 코드 디렉터리에서 사용된 폴더 이름을 사용하지 않았습니다.
* **node_modules** - 빌드에 사용되는 node 서드파티 모듈.
* **out** - `ninja`의 임시 출력 디렉터리.
* **dist** - 배포용 바이너리를 빌드할 때 사용하는 `script/create-dist.py` 스크립트로부터 만들어지는 임시 디렉터리.
* **external_binaries** - `gyp`를 통한 빌드가 지원하지 않아 따로 다운로드된 서드파티 프레임워크 바이너리들.

View file

@ -1,114 +0,0 @@
# Distribución de aplicaciones
Para distribuir tu aplicación con Electron, debes nombrar al directorio de tu aplicación
como `app`, y ponerlo bajo el directorio de recursos de Electron (en OSX es `Electron.app/Contents/Resources/`,
en Linux y Windows es `resources/`):
En OSX:
```text
electron/Electron.app/Contents/Resources/app/
├── package.json
├── main.js
└── index.html
```
En Windows y Linux:
```text
electron/resources/app
├── package.json
├── main.js
└── index.html
```
Posteriormente ejecutas `Electron.app` (o `electron` en Linux, `electron.exe` en Windows),
y Electron iniciará la aplicación. El directorio `electron` será la distribución que recibirán los usuarios finales.
## Empaquetando tu aplicación como un archivo
Además de copiar todos tus archivos fuente para la distribución, también puedes
empaquetar tu aplicación como un archivo [asar](https://github.com/atom/asar)
y de esta forma evitar la exposición del código fuente de tu aplicación a los usuarios.
Para usar un archivo `asar` en reemplazo de la carpeta `app`, debes renombrar
el archivo a `app.asar`, y ponerlo bajo el directorio de recursos de Electron (como arriba),
Electron intentará leer el archivo y ejecutar la aplicación desde él.
En OS X:
```text
electron/Electron.app/Contents/Resources/
└── app.asar
```
En Windows y Linux:
```text
electron/resources/
└── app.asar
```
Más detalles en [Empaquetamiento de aplicaciones](application-packaging-es.md).
## Rebranding con binarios descargados
Luego de empaquetar tu aplicación con Electron, podría ser útil agregar tu marca
antes de realizar la distribución.
### Windows
Puedes renombrar `electron.exe` a cualquier nombre que desees, y editar su ícono y otras informaciones
con herramientas como [rcedit](https://github.com/atom/rcedit) o [ResEdit](http://www.resedit.net).
### OS X
Puedes renombrar `Electron.app` a cualquier nombre que desees. También debes modificar los campos
`CFBundleDisplayName`, `CFBundleIdentifier` y `CFBundleName` en los siguientes archivos:
* `Electron.app/Contents/Info.plist`
* `Electron.app/Contents/Frameworks/Electron Helper.app/Contents/Info.plist`
También puedes renombrar el helper de la aplicación para evitar que aparezca como `Electron Helper`
en el Monitor de Actividades.
La estructura de una aplicación renombrada sería así:
```
MyApp.app/Contents
├── Info.plist
├── MacOS/
│   └── MyApp
└── Frameworks/
├── MyApp Helper EH.app
| ├── Info.plist
| └── MacOS/
|    └── MyApp Helper EH
├── MyApp Helper NP.app
| ├── Info.plist
| └── MacOS/
|    └── MyApp Helper NP
└── MyApp Helper.app
├── Info.plist
└── MacOS/
   └── MyApp Helper
```
### Linux
Puedes renombrar el ejectuable `electron` a cualquier nombre que desees.
## Rebranding desde el código fuente de Electron
También es posible agregar tu marca a Electron mediante un build personalizado.
Para realizar esto debes modificar el archivo `atom.gyp`.
### grunt-build-atom-shell
La modificación del código de Electron para agregar tu marca puede resultar complicada, una tarea Grunt
se ha creado para manejar esto de forma automatizada:
[grunt-build-atom-shell](https://github.com/paulcbetts/grunt-build-atom-shell).
Esta tarea se encargará de modificar el archivo `.gyp`, compilar el código
y reconstruir los módulos nativos de la aplicación para que coincidan con el nuevo nombre.

View file

@ -1,138 +0,0 @@
# 어플리케이션 배포
Electron 어플리케이션을 배포할 때는 어플리케이션 폴더의 이름을 `app`으로 지정한 후 Electron 실행파일의 리소스 디렉터리에 집어넣어야합니다.
리소스 디렉터리는 OS X에선 `Electron.app/Contents/Resources/` Windows와 Linux에선 `resources/` 입니다.
예제:
OS X의 경우:
```text
electron/Electron.app/Contents/Resources/app/
├── package.json
├── main.js
└── index.html
```
Windows 와 Linux의 경우:
```text
electron/resources/app
├── package.json
├── main.js
└── index.html
```
그리고 `Electron.app`을 실행하면(Linux에선 `electron` Windows에선 `electron.exe`입니다) Electron은 해당 앱을 실행시킵니다.
최종 사용자에게는 이 `electron` 폴더(Electron.app)를 배포하면 됩니다.
## asar로 앱 패키징 하기
소스파일 전체를 복사해서 배포하는 것과는 별개로 [asar](https://github.com/atom/asar) 아카이브를 통해
어플리케이션의 소스코드가 사용자에게 노출되는 것을 방지할 수 있습니다.
`asar` 아카이브를 사용할 땐 단순히 `app` 폴더 대신에 어플리케이션을 패키징한 `app.asar` 파일로 대체하면됩니다.
이렇게 하면 Electron은 아카이브를 `app`폴더 대신 asar 아카이브를 기반으로 어플리케이션을 실행합니다.
OS X의 경우:
```text
electron/Electron.app/Contents/Resources/
└── app.asar
```
Windows 와 Linux의 경우:
```text
electron/resources/
└── app.asar
```
자세한 내용은 [어플리케이션 패키징](application-packaging-ko.md)에서 찾아볼 수 있습니다.
## 다운로드한 바이너리의 리소스를 앱에 맞게 수정하기
어플리케이션을 Electron에 번들링한 후 해당 어플리케이션에 맞게 리브랜딩 할 수 있습니다.
### Windows
`electron.exe`을 원하는 이름으로 변경할 수 있습니다.
그리고 [rcedit](https://github.com/atom/rcedit) 또는 [ResEdit](http://www.resedit.net)를 사용하여 아이콘을 변경할 수 있습니다.
### OS X
`Electron.app`을 원하는 이름으로 변경할 수 있습니다. 그리고 다음 표시된 어플리케이션 내부 파일에서
`CFBundleDisplayName`, `CFBundleIdentifier` and `CFBundleName` 필드를 원하는 이름으로 변경해야합니다:
* `Electron.app/Contents/Info.plist`
* `Electron.app/Contents/Frameworks/Electron Helper.app/Contents/Info.plist`
또한 helper 앱이 프로세스 모니터에 `Electron Helper`로 나오지 않도록 이름을 변경할 수 있습니다.
하지만 반드시 내부 및 모든 helper 앱의 이름을 변경해야 합니다.
어플리케이션 아이콘은 `Electron.app/Contents/Resources/atom.icns`을 원하는 아이콘으로 변경하면 됩니다.
원하는 이름으로 바꾼 어플리케이션 예제:
```
MyApp.app/Contents
├── Info.plist
├── MacOS/
│   └── MyApp
└── Frameworks/
├── MyApp Helper EH.app
| ├── Info.plist
| └── MacOS/
|    └── MyApp Helper EH
├── MyApp Helper NP.app
| ├── Info.plist
| └── MacOS/
|    └── MyApp Helper NP
└── MyApp Helper.app
├── Info.plist
└── MacOS/
   └── MyApp Helper
```
### Linux
실행파일 `electron`의 이름을 원하는 대로 바꿀 수 있습니다.
리눅스 어플리케이션의 아이콘은 [.desktop](https://developer.gnome.org/integration-guide/stable/desktop-files.html.en) 파일을 사용하여 지정할 수 있습니다.
### 역주-자동화
배포시에 Electron의 리소스를 일일이 수정하는 것은 매우 귀찮고 복잡합니다.
하지만 이 작업을 자동화 시킬 수 있는 몇가지 방법이 있습니다:
* [electron-builder](https://github.com/loopline-systems/electron-builder)
* [electron-packager](https://github.com/maxogden/electron-packager)
## Electron 소스코드를 다시 빌드하여 리소스 수정하기
또한 Electron 소스코드를 다시 빌드할 때 어플리케이션 이름을 변경할 수 있습니다.
`GYP_DEFINES` 환경변수를 사용하여 다음과 같이 다시 빌드할 수 있습니다:
__Windows__
```bash
> set "GYP_DEFINES=project_name=myapp product_name=MyApp"
> python script\clean.py
> python script\bootstrap.py
> python script\build.py -c R -t myapp
```
__Bash__
```bash
$ export GYP_DEFINES="project_name=myapp product_name=MyApp"
$ script/clean.py
$ script/bootstrap.py
$ script/build.py -c Release -t myapp
```
### grunt-build-atom-shell
Electron의 소스코드를 수정하고 다시 빌드하는 작업은 상당히 복잡합니다.
이를 해결하기 위해 [grunt-build-atom-shell](https://github.com/paulcbetts/grunt-build-atom-shell)를 사용하여 빌드를 자동화 시킬 수 있습니다.
이 툴을 사용하면 자동으로 `.gyp`파일을 수정하고 다시 빌드합니다. 그리고 어플리케이션의 네이티브 Node 모듈 또한 새로운 실행파일 이름으로 매치 시킵니다.

View file

@ -1,157 +0,0 @@
# Empaquetamiento de aplicaciones
Para proteger los recursos y el código fuente de tu aplicación, puedes optar por empaquetar
tu aplicación en un paquete [asar][asar].
## Generando un archivo `asar`
Un paquete [asar][asar] es un formato sencillo similar a tar, este formato concatena todos los archivos en uno,
Electron puede leer el contenido sin desempaquetar todos los archivos.
A continuación, los pasos para empaquetar tu aplicación con `asar`:
### 1. Instalar asar
```bash
$ npm install -g asar
```
### 2. Empaquetar utilizando `asar pack`
```bash
$ asar pack your-app app.asar
```
## Utilizando los paquetes `asar`
En Electron existen dos tipos de APIs: las APIs de Node, proveídas por Node.js,
y las APIs Web, proveídas por Chromium. Ambas APIs soportan la lecutra de paquetes `asar`.
### API Node
Con parches especiales en Electron, las APIs de Node como `fs.readFile` and `require`
tratan los paquetes `asar` como directorios virtuales, y el contenido es accesible como si se tratara
de archivos normales en el sistema de archivos.
Por ejemplo, supongamos que tenemos un paquete `example.asar` bajo `/path/to`:
```bash
$ asar list /path/to/example.asar
/app.js
/file.txt
/dir/module.js
/static/index.html
/static/main.css
/static/jquery.min.js
```
Leer un archivo de nuestro paquete `asar`:
```javascript
var fs = require('fs');
fs.readFileSync('/path/to/example.asar/file.txt');
```
Listar todos los archivos de la raíz:
```javascript
var fs = require('fs');
fs.readdirSync('/path/to/example.asar');
```
Utilizar un módulo que se encuentra dentro del archivo:
```javascript
require('/path/to/example.asar/dir/module.js');
```
También puedes mostrar una página web contenida en un `asar` utilizando `BrowserWindow`.
```javascript
var BrowserWindow = require('browser-window');
var win = new BrowserWindow({width: 800, height: 600});
win.loadUrl('file:///path/to/example.asar/static/index.html');
```
### API Web
En una págin web, los archivos que se encuentran en el paquete son accesibles a través del protocolo `file:`.
Al igual que la API Node, los paquetes `asar` son tratados como directorios.
Por ejemplo, para obtener un archivo con `$.get`:
```html
<script>
var $ = require('./jquery.min.js');
$.get('file:///path/to/example.asar/file.txt', function(data) {
console.log(data);
});
</script>
```
### Utilizando un paquete `asar` como un archivo normal
En algunas situaciones necesitaremos acceder al paquete `asar` como archivo, por ejemplo,
si necesitaramos verificar la integridad del archivo con un checksum.
Para casos así es posible utilizar el módulo `original-fs`, que provee la API `fs` original:
```javascript
var originalFs = require('original-fs');
originalFs.readFileSync('/path/to/example.asar');
```
## Limitaciones de la API Node:
A pesar de que hemos intentado que los paquetes `asar` funcionen como directorios de la mejor forma posible,
aún existen limitaciones debido a la naturaleza de bajo nivel de la API Node.
### Los paquetes son de sólo lecutra
Los paquetes `asar` no pueden ser modificados, por lo cual todas las funciones que modifiquen archivos
no funcionarán.
## Los directorios del paquete no pueden establecerse como working directories
A pesar de que los paquetes `asar` son manejados virtualmente como directorios,
estos directorios no existen en el sistema de archivos, por lo cual no es posible establecerlos
como working directory, el uso de la opción `cwd` en algunas APIs podría causar errores.
### Desempaquetamiento adicional en algunas APIs
La mayoría de las APIs `fs` pueden leer u obtener información sobre un archivo en un paquete `asar` sin
la necesidad de desempaquetarlo, pero algunas APIs requieren la ruta real. En estos casos Electron extraerá
el archivo a una ruta temporal. Esto agrega un overhead a algunas APIs.
Las APIs que requieren el desempaquetamiento adicional son:
* `child_process.execFile`
* `fs.open`
* `fs.openSync`
* `process.dlopen` - Utilizado po `require` en los módulos nativos
### Información falsa en `fs.stat`
El objeto `Stats` retornado por `fs.stat` y otras funciones relacionadas,
no es preciso, ya que los archivos del paquete `asar` no existen el sistema de archivos.
La utilización del objeto `Stats` sólo es recomendable para obtener el tamaño del archivo y/o
comprobar el tipo de archivo.
## Agregando archivos al paquete `asar`
Como se menciona arriba, algunas APIs de Node desempaquetarán archivos cuando exista una llamada
que los referencie, además de los problemas de rendimiento que esto podría ocasionar, también
podría accionar alertas falsas en software antivirus.
Para lidiar con esto, puedes desempaquetar algunos archivos utilizando la opción `--unpack`,
a continuación un ejemplo que excluye las librerías compartidas de los módulos nativos:
```bash
$ asar pack app app.asar --unpack *.node
```
Después de ejecutar este comando, además del archivo `app.asar`, también se creará
un directorio `app.asar.unpacked`, que contendrá los archivos desempaquetados.
Este directorio deberá copiarse junto con el archivo `app.asar` a la hora de distribuir la aplicación.
[asar]: https://github.com/atom/asar

View file

@ -1,150 +0,0 @@
# 어플리케이션 패키징
Windows에서 일어나는 긴 경로 이름에 대한 [issues](https://github.com/joyent/node/issues/6960)를 완화하고 `require` 속도를 약간 빠르게 하며
어플리케이션의 리소스와 소스코드를 유저로부터 보호하기 위해 어플리케이션을 [asar][asar] 아카이브로 패키징 할 수 있습니다.
## `asar` 아카이브 생성
[asar][asar]아카이브는 tar과 비슷한 포맷으로 모든 리소스를 하나의 파일로 만듭니다.
그리고 Electron은 압축해제 없이 임의로 모든 파일을 읽어들일 수 있습니다.
다음 몇가지 단계를 통해 어플리케이션을 `asar` 아카이브로 압축할 수 있습니다:
### 1. asar 유틸리티 설치
```bash
$ npm install -g asar
```
### 2. `asar pack` 커맨드로 앱 패키징
```bash
$ asar pack your-app app.asar
```
## `asar` 아카이브 사용하기
Electron은 Node.js로 부터 제공된 Node API와 Chromium으로부터 제공된 Web API 두가지의 API를 가지고 있습니다.
두 API 모두 `asar`에서 읽어들일 수 있도록 지원합니다.
### Node API
`fs.readFile``require` 같은 Node API들을 지원하기 위해 Electron에선 `asar` 아카이브가 가상의 디렉터리 구조를 가지도록
패치했습니다. 그래서 아카이브 내부에서 리소스들을 정상적인 파일 시스템처럼 접근할 수 있습니다.
예를 들어 `/path/to`라는 경로에 `example.asar`라는 아카이브가 있다고 가정하면:
```bash
$ asar list /path/to/example.asar
/app.js
/file.txt
/dir/module.js
/static/index.html
/static/main.css
/static/jquery.min.js
```
`asar` 아카이브에선 다음과 같이 파일을 읽을 수 있습니다:
```javascript
var fs = require('fs');
fs.readFileSync('/path/to/example.asar/file.txt');
```
아카이브 내의 루트 디렉터리를 리스팅합니다:
```javascript
var fs = require('fs');
fs.readdirSync('/path/to/example.asar');
```
아카이브 안의 모듈 사용하기:
```javascript
require('/path/to/example.asar/dir/module.js');
```
`BrowserWindow` 클래스를 이용해 원하는 웹 페이지도 표시할 수 있습니다:
```javascript
var BrowserWindow = require('browser-window');
var win = new BrowserWindow({width: 800, height: 600});
win.loadUrl('file:///path/to/example.asar/static/index.html');
```
### Web API
웹 페이지 내에선 아카이브 내의 파일을 `file:` 프로토콜을 사용하여 요청할 수 있습니다.
이 또한 Node API와 같이 가상 디렉터리 구조를 가집니다.
예를 들어 jQuery의 `$.get`을 사용하여 파일을 가져올 수 있습니다:
```html
<script>
var $ = require('./jquery.min.js');
$.get('file:///path/to/example.asar/file.txt', function(data) {
console.log(data);
});
</script>
```
### `asar` 아카이브를 일반 파일로 취급하기
`asar` 아카이브의 체크섬(checksum)등을 검사하기 위해선 `asar` 아카이브를 파일 그대로 읽어들여야 할 필요가 있습니다.
이 작업을 하기 위해 `original-fs`라고 하는 빌트인 모듈을 `fs` 모듈 대신에 사용할 수 있습니다.
이 모듈은 `asar` 지원이 빠져있습니다. 즉 파일 그대로를 읽어들입니다:
```javascript
var originalFs = require('original-fs');
originalFs.readFileSync('/path/to/example.asar');
```
## Node API의 한계
`asar` 아카이브를 Node API가 최대한 디렉터리 구조로 작동하도록 노력해왔지만 여전히 저수준(low-level nature) Node API 때문에 한계가 있습니다.
### 아카이브는 읽기 전용입니다
아카이브는 수정할 수 없으며 기본적으로는 Node API로 파일을 수정할 수 있지만 `asar` 아카이브에선 작동하지 않습니다.
### 아카이브 안의 디렉터리를 작업 경로로 설정하면 안됩니다
`asar` 아카이브는 디렉터리처럼 사용할 수 있도록 구현되었지만 그것은 실제 파일시스템의 디렉터리가 아닌 가상의 디렉터리입니다.
그런 이유로 몇몇 API에서 지원하는 `cwd` 옵션을 `asar` 아카이브 안의 디렉터리 경로로 지정하면 나중에 문제가 발생할 수 있습니다.
### 특정 API로 인한 예외적인 압축 해제
많은 `fs` API가 `asar` 아카이브의 압축을 해제하지 않고 바로 아카이브를 읽거나 정보를 가져올 수 있으나
몇몇 API는 시스템의 실제 파일의 경로를 기반으로 작동하므로 이 API들을 사용할 땐 Electron은
이 API가 원할하게 작동할 수 있도록 하기 위해 임시경로에 해당 파일들의 압축을 해제합니다. 이 작업은 약간의 오버헤드를 불러 일으킬 수 있습니다.
해당하는 API 함수는 다음과 같습니다:
* `child_process.execFile`
* `fs.open`
* `fs.openSync`
* `process.dlopen` - Used by `require` on native modules
### `fs.stat`의 잘못된 스테이터스 정보
`fs.stat` 로 부터 반환되는 `Stats` 객체와 비슷한 API들은 `asar` 아카이브를 타겟으로 할 경우 예측된 디렉터리 피일 정보를 가집니다.
왜냐하면 아카이브의 디렉터리 경로는 실제 파일시스템에 존재하지 않기 때문입니다.
그러한 이유로 파일 크기와 파일 타입 등을 확인할 때 `Stats` 객체를 신뢰해선 안됩니다.
## `asar` 아카이브에 미리 압축 해제된 파일 추가하기
전술한 바와 같이 몇몇 Node API는 호출 시 해당 파일을 임시폴더에 압축을 해제합니다.
따로 성능문제가 발생할 수 있습니다. 그리고 백신 소프트웨어의 잘못된 오진을 일으킬 수도 있습니다.
이 문제를 해결하려면 `--unpack` 옵션을 활용하여 파일을 압축이 풀려진 상태로 유지해야 합니다.
다음의 예제는 node 네이티브 모듈의 공유 라이브러리를 unpack 상태로 유지합니다:
```bash
$ asar pack app app.asar --unpack *.node
```
커맨드를 실행한 후 같은 디렉터리에 `app.asar` 파일 외에 `app.asar.unpacked` 폴더가 같이 생성됩니다.
이 폴더안에 unpack 옵션에서 설정한 파일들이 압축이 풀린 상태로 포함되어 있습니다.
유저에게 어플리케이션을 배포할 때 반드시 해당 폴더도 같이 배포하여야합니다.
[asar]: https://github.com/atom/asar

View file

@ -1,45 +0,0 @@
# Depurando el proceso principal
Los devtools sólo pueden depurar las páginas web (el código del proceso renderer).
Para depurar el código del proceso principal, Electron provee dos opciones para la línea de comandos: `--debug` y `--debug-brk`.
## Opciones para la línea de comandos
### `--debug=[port]`
Esta opción escuchará mensajes del protocolo de depuración V8 en `port`, por defecto `port` es `5858`.
### `--debug-brk=[port]`
Similar a `--debug` pero realiza una pausa en la primera línea del script.
## Utilizando node-inspector para depuración
__Nota:__ Electron utiliza node v0.11.13, esta versión aún no funciona bien con node-inspector,
el proceso principal podría fallar al inspeccionar el objeto `process`.
### 1. Iniciar [node-inspector][node-inspector]
```bash
$ node-inspector
```
### 2. Activar el modo de depuración en Electron
Es posible iniciar Electron con la opción de depuración:
```bash
$ electron --debug=5858 your/app
```
o, pausar el script en la primera línea:
```bash
$ electron --debug-brk=5858 your/app
```
### 3. Cargar la interfaz del depurador
Abre http://127.0.0.1:8080/debug?ws=127.0.0.1:8080&port=5858 en Chrome.
[node-inspector]: https://github.com/node-inspector/node-inspector

View file

@ -1,45 +0,0 @@
# 메인 프로세스 디버깅하기
브라우저 창의 개발자 콘솔은 랜더러 프로세스의 스크립트만 디버깅이 가능합니다. (다시말해 웹 페이지)
메인 프로세스의 디버깅 방법을 제공하기 위해 Electron은 `--debug``--debug-brk` 스위치들을 제공합니다.
## 커맨드 라인 스위치(command line switches)
### `--debug=[port]`
이 스위치를 사용하면 Electron은 지정한 `port`에 V8 디버거 프로토콜을 리스닝합니다. `port``5858`이 기본적으로 사용됩니다.
### `--debug-brk=[port]`
`--debug`와 비슷하지만 스크립트의 첫번째 라인에서 일시정지합니다.
## node-inspector로 디버깅 하기
__주의:__ Electron은 node v0.11.13 버전을 사용합니다. node-inspector는 현재 아주 잘 작동하지 않습니다.
그리고 메인 프로세스의 `process`를 node-inspector 콘솔 내에서 검사할 경우 크래시가 발생할 수 있습니다.
### 1. [node-inspector][node-inspector] 서버 시작
```bash
$ node-inspector
```
### 2. Electron용 디버그 모드 활성화
다음과 같이 debung 플래그로 Electron을 실행할 수도 있습니다:
```bash
$ electron --debug=5858 your/app
```
또는 스크립트 첫번째 라인에서 일시정지:
```bash
$ electron --debug-brk=5858 your/app
```
### 3. 디버그 UI 로드
Chrome 브라우저에서 http://127.0.0.1:8080/debug?ws=127.0.0.1:8080&port=5858 주소에 접속합니다. (기본포트 또는 지정한 포트로 접속)
[node-inspector]: https://github.com/node-inspector/node-inspector

View file

@ -1,171 +0,0 @@
# Integración con el entorno de escritorio
Los sistemas operativos proveen diferentes características para integrar aplicaciones
en sus entornos de escritorio. Por ejemplo, en Windows, las aplicaciones pueden agregar accesos directos
en la JumpList de la barra de tareas, y en Mac, las aplicaciones pueden agregar un menú personalizado en el dock.
Esta guía explica cómo integrar tu aplicación en esos entornos de escritorio a través de las APIs de Electron.
## Documentos recientes (Windows y OS X)
Windows y OS X proveen un acceso sencillo a la lista de documentos recientes.
__JumpList:__
![JumpList, Archivos recientes](http://i.msdn.microsoft.com/dynimg/IC420538.png)
__Menú Dock:__
<img src="https://cloud.githubusercontent.com/assets/639601/5069610/2aa80758-6e97-11e4-8cfb-c1a414a10774.png" height="353" width="428" >
Para agregar un archivo a la lista de documentos recientes, puedes utilizar:
[app.addRecentDocument][addrecentdocument] API:
```javascript
var app = require('app');
app.addRecentDocument('/Users/USERNAME/Desktop/work.type');
```
También puedes utilizar [app.clearRecentDocuments](clearrecentdocuments) para vaciar la lista de documentos recientes:
```javascript
app.clearRecentDocuments();
```
### Notas sobre Windows
Para activar esta característica en Windows, tu aplicación debe registrar un handler
para el tipo de archivo que quieres utilizar, de lo contrario el archivo no aparecerá
en la JumpList, aún después de agregarlo. Puedes encontrar más información sobre el proceso de
registrar tu aplicación en [Application Registration][app-registration].
Cuando un usuario haga click en un archivo de la JumpList, una nueva instancia de tu aplicación
se iniciará, la ruta del archivo se agregará como un argumento de la línea de comandos.
### Notas sobre OS X
Cuando un archivo es solicitado desde el menú de documentos recientes, el evento `open-file`
del módulo `app` será emitido.
## Menú dock personalizado (OS X)
OS X permite a los desarrolladores definir un menú personalizado para el dock,
el cual usualmente contiene algunos accesos directos a las características más comunes
de tu aplicación:
__Menú dock de Terminal.app:__
<img src="https://cloud.githubusercontent.com/assets/639601/5069962/6032658a-6e9c-11e4-9953-aa84006bdfff.png" height="354" width="341" >
Para establecer tu menú dock, puedes utilizar la API `app.dock.setMenu`, la cual sólo está disponible para OSX:
```javascript
var app = require('app');
var Menu = require('menu');
var dockMenu = Menu.buildFromTemplate([
{ label: 'New Window', click: function() { console.log('New Window'); } },
{ label: 'New Window with Settings', submenu: [
{ label: 'Basic' },
{ label: 'Pro'}
]},
{ label: 'New Command...'}
]);
app.dock.setMenu(dockMenu);
```
## Tareas de usuario (Windows)
En Windows puedes especificar acciones personalizadas en la categoría `Tasks` del JumpList,
tal como menciona MSDN:
> Las aplicaciones definen tareas basadas en las características del programa
> y las acciones clave que se esperan de un usuario. Las tareas deben ser
> libres de contexto, es decir, la aplicación no debe encontrarse en ejecución
> para que estas acciones funcionen. También deberían ser las acciones estadísticamente
> más comunes que un usuario normal realizaría en tu aplicación, como por ejemplo,
> redactar un mensaje de correo electrónico, crear un documento en el procesador de textos,
> ejecutar una aplicación en cierto modo, o ejecutar alguno de sus subcomandos. Una aplicación
> no debería popular el menú con características avanzadas que el usuario estándar no necesita
> ni con acciones que sólo se realizan una vez, como por ejemplo, el registro. No utilices
> las tareas para mostrar elementos promocionales como actualizaciones u ofertas especiales.
>
> Es recomendable que la lista de tareas sea estática. Debe mantenerse a pesar
> de los cambios de estado de la aplicación. Aunque exista la posibilidad de variar
> el contenido de la lista dinámicamente, debes considerar que podría ser confuso
> para un usuario que no espera que el destino de la lista cambie.
__Tareas de Internet Explorer:__
![IE](http://i.msdn.microsoft.com/dynimg/IC420539.png)
A diferencia del menú dock en OS X, el cual es un menú real, las tareas de usuario en Windows
funcionan como accesos directos de aplicación, que al ser clickeados, lanzan el programa
con argumentos específicos.
Para establecer las tareas de usuario en tu aplicación, puedes utilizar:
[app.setUserTasks][setusertaskstasks] API:
```javascript
var app = require('app');
app.setUserTasks([
{
program: process.execPath,
arguments: '--new-window',
iconPath: process.execPath,
iconIndex: 0,
title: 'New Window',
description: 'Create a new window'
}
]);
```
Para purgar la lista de tareas, puedes llamar a `app.setUserTasks` con un array vacío:
```javascript
app.setUserTasks([]);
```
Las tareas de usuario aún serán visibles después de cerrar tu aplicación, por lo cual
el ícono y la ruta del programa deben existir hasta que la aplicación sea desinstalada.
## Accesos directos en el lanzador Unity (Linux)
En Unity, es posible agregar algunas entradas personalizadas, modificando el archivo `.desktop`,
ver [Adding shortcuts to a launcher][unity-launcher].
__Accesos directos de Audacious:__
![audacious](https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles?action=AttachFile&do=get&target=shortcuts.png)
## Barra de progreso en la barra de tareas (Windows y Unity)
En Windows, un botón en la barra de tareas puede utilizarse para mostrar una barra de progreso. Esto permite
que una ventana muestre la información de progreso al usuario, sin que el usuario tenga la ventana de la aplicación activa.
El entorno de escritorio Unity también posee una característica similar que permite mostrar una barra de progreso en el lanzador.
__Barra de progreso en un botón de la barra de herramientas:__
![Taskbar Progress Bar](https://cloud.githubusercontent.com/assets/639601/5081682/16691fda-6f0e-11e4-9676-49b6418f1264.png)
__Barra de progreso en el lanzador Unity:__
![Unity Launcher](https://cloud.githubusercontent.com/assets/639601/5081747/4a0a589e-6f0f-11e4-803f-91594716a546.png)
Para establecer la barra de progreso de una ventana, puedes utilizar
[BrowserWindow.setProgressBar][setprogressbar] API:
```javascript
var window = new BrowserWindow({...});
window.setProgressBar(0.5);
```
[addrecentdocument]: ../api/app.md#appaddrecentdocumentpath
[clearrecentdocuments]: ../api/app.md#appclearrecentdocuments
[setusertaskstasks]: ../api/app.md#appsetusertaskstasks
[setprogressbar]: ../api/browser-window.md#browserwindowsetprogressbarprogress
[setrepresentedfilename]: ../api/browser-window.md#browserwindowsetrepresentedfilenamefilename
[setdocumentedited]: ../api/browser-window.md#browserwindowsetdocumenteditededited
[app-registration]: http://msdn.microsoft.com/en-us/library/windows/desktop/ee872121(v=vs.85).aspx
[unity-launcher]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher

View file

@ -1,222 +0,0 @@
# 데스크톱 환경 통합
어플리케이션을 배포할 서로 다른 운영체제 시스템의 환경과 기능에 맞춰 사용 환경을 통합할 수 있습니다.
예를 들어 Windows에선 태스크바의 JumpList에 바로가기를 추가할 수 있고 Mac(OS X)에선 dock menu에 커스텀 메뉴를 추가할 수 있습니다.
이 가이드는 Electron API를 이용하여 각 운영체제 시스템의 기능을 활용하는 방법을 설명합니다.
## 최근 사용한 문서 (Windows & OS X)
Windows와 OS X는 dock menu나 JumpList등을 통하여 최근 문서 리스트에 쉽게 접근할 수 있습니다.
__JumpList:__
![JumpList 최근 문서](http://i.msdn.microsoft.com/dynimg/IC420538.png)
__어플리케이션 dock menu:__
<img src="https://cloud.githubusercontent.com/assets/639601/5069610/2aa80758-6e97-11e4-8cfb-c1a414a10774.png" height="353" width="428" >
파일을 최근 문서에 추가하려면 [app.addRecentDocument][addrecentdocument] API를 사용할 수 있습니다:
```javascript
var app = require('app');
app.addRecentDocument('/Users/USERNAME/Desktop/work.type');
```
그리고 [app.clearRecentDocuments](clearrecentdocuments) API로 최근 문서 리스트를 비울 수 있습니다:
```javascript
app.clearRecentDocuments();
```
### Windows에서 주의할 점
이 기능을 Windows에서 사용할 땐 운영체제 시스템에 어플리케이션에서 사용하는 파일 확장자가 등록되어 있어야 합니다.
그렇지 않은 경우 파일을 JumpList에 추가해도 추가되지 않습니다.
어플리케이션 등록에 관련된 API의 모든 내용은 [Application Registration][app-registration]에서 찾아볼 수 있습니다.
유저가 JumpList에서 파일을 클릭할 경우 클릭된 파일의 경로가 커맨드 라인 인자로 추가되어 새로운 인스턴스의 어플리케이션이 실행됩니다.
### OS X에서 주의할 점
파일이 최근 문서 메뉴에서 요청될 경우 `app` 모듈의 `open-file` 이벤트가 호출됩니다.
## 커스텀 독 메뉴 (OS X)
OS X는 개발자가 dock에 커스텀 메뉴를 만들 수 있도록 허용하고 있습니다.
보통 어플리케이션의 특정 기능 바로가기를 만들 때 사용합니다:
__Terminal.app의 dock menu:__
<img src="https://cloud.githubusercontent.com/assets/639601/5069962/6032658a-6e9c-11e4-9953-aa84006bdfff.png" height="354" width="341" >
커스텀 dock menu를 설정하려면 `app.dock.setMenu` API를 사용하면 됩니다. OS X에서만 사용 가능합니다:
```javascript
var app = require('app');
var Menu = require('menu');
var dockMenu = Menu.buildFromTemplate([
{ label: 'New Window', click: function() { console.log('New Window'); } },
{ label: 'New Window with Settings', submenu: [
{ label: 'Basic' },
{ label: 'Pro'}
]},
{ label: 'New Command...'}
]);
app.dock.setMenu(dockMenu);
```
## 사용자 작업 (Windows)
Windows에선 JumpList의 `Tasks` 카테고리에 원하는 작업을 설정할 수 있습니다.
MSDN에선 해당 기능을 다음과 같이 설명하고 있습니다:
> 어플리케이션 작업은 프로그램의 기능 그리고 주요사양 두가지를 기반으로 유저의 행동을 예측하여 정의합니다.
> 실행할 필요가 없는 어플리케이션 작업은 작동하지 않을 때 반드시 context-free를 유지해야 합니다.
> 작업은 일반 사용자가 프로그램을 실행하거나 이메일 프로그램으로 이메일을 작성하거나 달력을 불러오고
> 워드 프로세서로 새 문서를 작성, 특정 모드, 부속 명령으로 프로그램을 실행하는 등의
> 통계적, 일반적으로 가장 많이 사용되는 작업인지를 고려해야 합니다.
> 어플리케이션 작업은 일반 유저가 필요로 하지 않는 고급 기능을 조잡하게 채우거나 등록과 같은 일회성의 작업을 포함해선 안됩니다.
> 작업에 특별 이벤트 또는 업그레이드 등의 홍보성 작업을 추가하면 안됩니다.
>
> 작업 리스트는 가능한 한 정적으로 유지되는 것을 적극 권장합니다.
> 이것은 동일한 상태 또는 응용 프로그램의 상태에 관계없이 유지되어야 합니다.
> 작업 목록은 동적으로 변경할 수 있지만 몇몇 유저는 예상하지 못한 작업 목록 변경에 혼동할 수 있다는 점을 고려해야 합니다.
__Internet Explorer의 작업:__
![IE](http://i.msdn.microsoft.com/dynimg/IC420539.png)
OS X의 말 그대로 메뉴로 작동하는 dock menu 와는 달리 Windows의 사용자 작업은 어플리케이션 바로가기처럼 작동합니다.
유저가 작업을 클릭할 시 설정한 인자와 함께 새로운 어플리케이션이 실행됩니다.
사용자 작업을 설정하려면 [app.setUserTasks][setusertaskstasks] API를 사용하여 구현할 수 있습니다:
```javascript
var app = require('app');
app.setUserTasks([
{
program: process.execPath,
arguments: '--new-window',
iconPath: process.execPath,
iconIndex: 0,
title: 'New Window',
description: 'Create a new window'
}
]);
```
작업 리스트를 비우려면 간단히 `app.setUserTasks` 메서드의 첫번째 인자에 빈 배열을 넣어 호출하면 됩니다:
```javascript
app.setUserTasks([]);
```
사용자 작업 리스트는 어플리케이션이 삭제되지 않는 한 종료되어도 태스크바에 보존됩니다. 이러한 이유로 반드시 프로그램 경로와 아이콘 경로를 지정해야 합니다.
## 섬네일 툴바
Windows에선 작업 표시줄의 어플리케이션 선택시 나오는 미리보기에 특정한 섬네일 툴바를 추가할 수 있습니다.
이 기능은 유저가 윈도우를 활성화 하지 않고 특정한 커맨드를 실행시킬 수 있도록 할 수 있습니다.
MSDN의 설명에 의하면:
> 이 툴바는 표준 툴바의 공통 컨트롤과 비슷한 역할을 합니다. 버튼은 최대 7개 까지 만들 수 있습니다.
> 각 버튼의 구조엔 ID, 이미지, 툴팁, 상태등이 정의되어있습니다. 태스크바에 구조가 전달되면 어플리케이션이
> 상태에 따라 버튼을 숨기거나, 활성화하거나, 비활성화 할 수 있습니다.
>
> 예를 들어, 윈도우 미디어 플레이어는(WMP) 기본적으로
> 미디어 플레이어가 공통적으로 사용하는 재생, 일시정지, 음소거, 정지등의 컨트롤을 포함하고 있습니다.
__Windows Media Player의 섬네일 툴바:__
![player](https://i-msdn.sec.s-msft.com/dynimg/IC420540.png)
[BrowserWindow.setThumbarButtons][setthumbarbuttons] API를 통해 어플리케이션에 섬네일 툴바를 설정할 수 있습니다:
```javascript
var BrowserWindow = require('browser-window');
var path = require('path');
var win = new BrowserWindow({
width: 800,
height: 600
});
win.setThumbarButtons([
{
tooltip: "button1",
icon: path.join(__dirname, 'button1.png'),
click: function() { console.log("button2 clicked"); }
},
{
tooltip: "button2",
icon: path.join(__dirname, 'button2.png'),
flags:['enabled', 'dismissonclick'],
click: function() { console.log("button2 clicked."); }
}
]);
```
섬네일 툴바를 비우려면 간단히 `BrowserWindow.setThumbarButtons` API에 빈 배열을 전달하면 됩니다:
```javascript
win.setThumbarButtons([]);
```
## Unity 런처 숏컷 기능 (Linux)
Unity 환경에선 `.desktop` 파일을 수정함으로써 런처에 새로운 커스텀 엔트리를 추가할 수 있습니다. [Adding shortcuts to a launcher][unity-launcher] 가이드를 참고하세요.
__Audacious의 런처 숏컷:__
![audacious](https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles?action=AttachFile&do=get&target=shortcuts.png)
## Taskbar progress 기능 (Windows & Unity)
Windows에선 태스크바의 어플리케이션 버튼에 progress bar를 추가할 수 있습니다.
이 기능은 사용자가 어플리케이션의 창을 열지 않고도 어플리케이션의 작업의 상태 정보를 시각적으로 보여줄 수 있도록 해줍니다.
또한 Unity DE도 런처에 progress bar를 부착할 수 있습니다.
__태스크바 버튼의 progress bar:__
![Taskbar Progress Bar](https://cloud.githubusercontent.com/assets/639601/5081682/16691fda-6f0e-11e4-9676-49b6418f1264.png)
__Unity 런처의 progress bar:__
![Unity Launcher](https://cloud.githubusercontent.com/assets/639601/5081747/4a0a589e-6f0f-11e4-803f-91594716a546.png)
이 기능은 [BrowserWindow.setProgressBar][setprogressbar] API를 사용하여 구현할 수 있습니다:
```javascript
var window = new BrowserWindow({...});
window.setProgressBar(0.5);
```
## 윈도우 대표 파일 제시 (OS X)
OS X는 윈도우에서 대표 파일을 설정할 수 있습니다. 쉽게 말해 타이틀바에서 파일 아이콘을 볼 수 있을 때 사용자가 Command-Click 또는 Control-Click 할 경우 파일 경로 팝업이 보여집니다.
또한 윈도우의 상태도 지정할 수 있습니다. 쉽게 말해 로드된 문서의 수정여부를 타이틀바 파일 아이콘에 표시할 수 있습니다.
__대표 파일 팝업 메뉴:__
<img src="https://cloud.githubusercontent.com/assets/639601/5082061/670a949a-6f14-11e4-987a-9aaa04b23c1d.png" height="232" width="663" >
대표 파일 관련 API는 [BrowserWindow.setRepresentedFilename][setrepresentedfilename] 과 [BrowserWindow.setDocumentEdited][setdocumentedited]를 사용할 수 있습니다:
```javascript
var window = new BrowserWindow({...});
window.setRepresentedFilename('/etc/passwd');
window.setDocumentEdited(true);
```
[addrecentdocument]: ../api/app-ko.md#appaddrecentdocumentpath
[clearrecentdocuments]: ../api/app-ko.md#appclearrecentdocuments
[setusertaskstasks]: ../api/app-ko.md#appsetusertaskstasks
[setprogressbar]: ../api/browser-window-ko.md#browserwindowsetprogressbarprogress
[setrepresentedfilename]: ../api/browser-window-ko.md#browserwindowsetrepresentedfilenamefilename
[setdocumentedited]: ../api/browser-window-ko.md#browserwindowsetdocumenteditededited
[app-registration]: http://msdn.microsoft.com/en-us/library/windows/desktop/ee872121(v=vs.85).aspx
[unity-launcher]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher
[setthumbarbuttons]: ../api/browser-window.md#browserwindowsetthumbarbuttonsbuttons

View file

@ -1,49 +0,0 @@
# Extensión DevTools
Para facilitar la depuración, Electron provee un soporte básico para la extensión
[Chrome DevTools Extension][devtools-extension].
Para la mayoría de las extensiones devtools, simplemente puedes descargar el código fuente
y utilizar `BrowserWindow.addDevToolsExtension` para cargarlas, las extensiones cargadas
serán recordadas para que no sea necesario llamar a la función cada vez que creas una ventana.
Por ejemplo, para usar la extensión [React DevTools Extension](https://github.com/facebook/react-devtools), primero debes descargar el código fuente:
```bash
$ cd /some-directory
$ git clone --recursive https://github.com/facebook/react-devtools.git
```
Luego cargas la aplicación en Electron, abriendo devtools en cualquier ventana,
y ejecutando este código en la consola devtools:
```javascript
require('remote').require('browser-window').addDevToolsExtension('/some-directory/react-devtools');
```
Para remover una extensión, puedes utilizar `BrowserWindow.removeDevToolsExtension`
especificando el nombre, y esta ya no se cargará la siguiente vez que abras devtools:
```javascript
require('remote').require('browser-window').removeDevToolsExtension('React Developer Tools');
```
## Formato de las extensiones devtools
Idealmente todas las extensiones devtools escritas para Chrome pueden ser cargadas por Electron,
pero para ello deben estar en un directorio plano, las extensiones empaquetadas como `crx`
no pueden ser cargadas por Chrome a no ser que halles una forma de extraerlas a un directorio.
## Páginas en segundo plano (background)
Electron no soporta la característica de páginas en segundo plano de las extensiones de Chrome,
las extensiones que utilizan esta característica podrían no funcionar.
## APIs `chrome.*`
Algunas extensiones utilizan las APIs `chrome.*`, hemos realizado un esfuerzo
para implementar esas APIs en Electron, sin embargo no han sido implementadas en su totalidad.
Dado que no todas las funciones `chrome.*` han sido implementadas, si la extensión devtools está utilizando otras APIs más allá de `chrome.devtools.*`, es muy probable que no funcione. Puedes reportar fallos en el issue tracker para que podamos agregar soporte a esas APIs.
[devtools-extension]: https://developer.chrome.com/extensions/devtools

View file

@ -1,47 +0,0 @@
# 개발자 콘솔 확장
어플리케이션의 디버깅을 쉽게 하기 위해 Electron은 기본적으로 [Chrome DevTools Extension][devtools-extension]을 지원합니다.
개발자 콘솔 확장기능은 간단하게 사용할 확장기능 플러그인의 소스코드를 다운로드한 후 `BrowserWindow.addDevToolsExtension` API를 이용하여
어플리케이션 내에 로드할 수 있습니다. 한가지 주의할 점은 확장기능 사용시 창이 생성될 때 마다 일일이 해당 API를 호출할 필요는 없습니다.
예시로 [React DevTools Extension](https://github.com/facebook/react-devtools)을 사용합니다.
먼저 소스코드를 다운로드 받습니다:
```bash
$ cd /some-directory
$ git clone --recursive https://github.com/facebook/react-devtools.git
```
그리고 개발자 콘솔이 열린 창에서 다음의 코드를 콘솔에 입력하면 확장기능을 로드할 수 있습니다:
```javascript
require('remote').require('browser-window').addDevToolsExtension('/some-directory/react-devtools');
```
확장기능을 unload 하고 콘솔을 다시 열 때 해당 확장기능이 로드되지 않도록 하려면 `BrowserWindow.removeDevToolsExtension` API를 사용하면 됩니다:
```javascript
require('remote').require('browser-window').removeDevToolsExtension('React Developer Tools');
```
## 개발자 콘솔 확장기능의 구성 형식
완벽하게 모든 개발자 콘솔 확장은 Chrome 브라우저를 위해 작성되었기 때문에 Electron에서도 로드할 수 있습니다.
하지만 반드시 확장기능은 소스코드 그대로의 디렉터리(폴더) 형태여야 합니다. 그래서 `crx` 등의 포맷으로 패키징된 확장기능의 경우
사용자가 직접 해당 패키지의 압축을 풀어서 로드하지 않는 이상은 Electron에서 해당 확장기능의 압축을 풀 방법이 없습니다.
## 백그라운드 페이지
현재 Electron은 Chrome에서 지원하는 백그라운드 페이지(background pages)를 지원하지 않습니다.
몇몇 확장기능은 이 기능에 의존하는 경우가 있는데 이 경우 해당 확장기능은 Electron에서 작동하지 않을 수 있습니다.
## `chrome.*` API
몇몇 Chrome 확장기능은 특정 기능을 사용하기 위해 `chrome.*` API를 사용하는데, Electron에선 이 API들을 구현하기 위해 노력했지만 안타깝게도 아직 모든 API가 구현되지는 않았습니다.
아직 모든 API가 구현되지 않았기 때문에 확장기능에서 `chrome.devtools.*` 대신 `chrome.*` API를 사용할 경우 확장기능이 제대로 작동하지 않을 수 있음을 감안해야 합니다.
만약 문제가 발생할 경우 Electron의 GitHub repo에 이슈를 올리면 해당 API를 추가하는데 많은 도움이 됩니다.
[devtools-extension]: https://developer.chrome.com/extensions/devtools

View file

@ -1,80 +0,0 @@
# Detección del evento en línea/fuera de línea
La detección de estos eventos puede ser implementada en el proceso renderer utilizando las APIs HTML5 estándar,
como en este ejemplo:
_main.js_
```javascript
var app = require('app');
var BrowserWindow = require('browser-window');
var onlineStatusWindow;
app.on('ready', function() {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html');
});
```
_online-status.html_
```html
<!DOCTYPE html>
<html>
<body>
<script>
var alertOnlineStatus = function() {
window.alert(navigator.onLine ? 'online' : 'offline');
};
window.addEventListener('online', alertOnlineStatus);
window.addEventListener('offline', alertOnlineStatus);
alertOnlineStatus();
</script>
</body>
</html>
```
Existen casos en donde necesitas responder a estos eventos desde el proceso principal.
El proceso principal no posee un objeto `navigator`, por lo tanto no puede detectar estos eventos directamente.
Es posible reenviar el evento al proceso principal mediante la utilidad de intercomunicación entre procesos (ipc):
_main.js_
```javascript
var app = require('app');
var ipc = require('ipc');
var BrowserWindow = require('browser-window');
var onlineStatusWindow;
app.on('ready', function() {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html');
});
ipc.on('online-status-changed', function(event, status) {
console.log(status);
});
```
_online-status.html_
```html
<!DOCTYPE html>
<html>
<body>
<script>
var ipc = require('ipc');
var updateOnlineStatus = function() {
ipc.send('online-status-changed', navigator.onLine ? 'online' : 'offline');
};
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
updateOnlineStatus();
</script>
</body>
</html>
```

View file

@ -1,80 +0,0 @@
# 온라인/오프라인 이벤트
온라인/오프라인 이벤트는 다음 예제와 같이 랜더러 프로세스에서 표준 HTML5 API를 이용하여 구현할 수 있습니다.
_main.js_
```javascript
var app = require('app');
var BrowserWindow = require('browser-window');
var onlineStatusWindow;
app.on('ready', function() {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html');
});
```
_online-status.html_
```html
<!DOCTYPE html>
<html>
<body>
<script>
var alertOnlineStatus = function() {
window.alert(navigator.onLine ? 'online' : 'offline');
};
window.addEventListener('online', alertOnlineStatus);
window.addEventListener('offline', alertOnlineStatus);
alertOnlineStatus();
</script>
</body>
</html>
```
필요한 경우 이 이벤트를 메인 프로세스로 보낼 수도 있습니다.
메인 프로세스는 `navigator` 오브젝트를 가지고 있지 않기 때문에 이 이벤트를 직접 사용할 수 없습니다.
이는 다음 예제와 같이 electron의 inter-process communication(ipc)유틸리티를 사용하여
이벤트를 메인 프로세스로 전달하는 것으로 해결할 수 있습니다.
_main.js_
```javascript
var app = require('app');
var ipc = require('ipc');
var BrowserWindow = require('browser-window');
var onlineStatusWindow;
app.on('ready', function() {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html');
});
ipc.on('online-status-changed', function(event, status) {
console.log(status);
});
```
_online-status.html_
```html
<!DOCTYPE html>
<html>
<body>
<script>
var ipc = require('ipc');
var updateOnlineStatus = function() {
ipc.send('online-status-changed', navigator.onLine ? 'online' : 'offline');
};
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
updateOnlineStatus();
</script>
</body>
</html>
```

View file

@ -1,154 +0,0 @@
# Intro
## Introducción
Electron permite la creación de aplicaciones de escritorio utilizando JavaScript puro, a través de un runtime con APIs nativas. Puedes verlo como una variante de io.js, enfocado en aplicaciones de escritorio, en vez de servidores web.
Esto no significa que Electron sea un binding de librerías GUI para JavaScript.
Electron utiliza páginas web como su GUI, por lo cual puedes verlo como un navegador Chromium mínimo,
controlado por JavaScript.
### El proceso principal (main process)
En Electron, el proceso que ejecuta el script `main` del `package.json` se llama __el proceso principal__.
El script que corre en el proceso principal puede crear páginas para mostrar la GUI.
### El proceso renderer (renderer process)
Dado que Electron utiliza Chromium para mostrar las páginas web,
también es utilizada la arquitectura multiproceso de Chromium.
Cada página web en Electron se ejecuta en su propio proceso,
el cual es llamado __el proceso renderer__.
En los navegadores normales, las páginas web usualmente se ejecutan en un entorno
sandbox y no tienen acceso a los recursos nativos. Los usuarios de Electron tienen el poder
de utilizar las APIs de io.js en las páginas web, permitiendo interacciones de bajo nivel con el sistema operativo.
### Diferencias entre el proceso principal y el proceso renderer
El proceso principal crea páginas web mediante instancias de `BrowserWindow`. Cada instancia de `BrowserWindow` ejecuta su propia página web y su propio proceso renderer.
Cuando una instancia de `BrowserWindow` es destruida, también su proceso renderer correspondiente acaba.
El proceso principal gestiona las páginas web y sus correspondientes procesos renderer.
Cada proceso renderer es aislado y sólo considera relevante la página web que corre en él.
En las páginas web, no está permitido llamar a APIs relacionadas a la GUI nativa
porque la gestión de los recursos GUI nativos es peligrosa, y tiende a que ocurran leaks de memoria.
Si deseas realizar operaciones GUI en una página web, el proceso renderer de la página web debe comunicarse
con el proceso principal, y solicitar a este que realice esas operaciones.
En Electron, hemos proveído el módulo [ipc](../api/ipc-renderer.md) para la comunicación
entre el proceso principal y el proceso renderer. Y también hay un módulo [remote](../api/remote.md)
para comunicación al estilo RPC.
## Escribe tu primera aplicación Electron
Generalmente, una aplicación Electron tendrá la siguiente estructura:
```text
your-app/
├── package.json
├── main.js
└── index.html
```
El formato de `package.json` es exactamente el mismo que cualquier módulo Node,
y el script especificado en el campo `main` será el script de arranque de tu aplicación,
a ser ejecutado por el proceso principal. Un ejemplo de `package.json` podría verse así:
```json
{
"name" : "your-app",
"version" : "0.1.0",
"main" : "main.js"
}
```
El `main.js` debería crear las ventanas y gestionar los eventos del sistema, un ejemplo típico sería:
example being:
```javascript
var app = require('app'); // Módulo para controlar el ciclo de vida de la aplicación.
var BrowserWindow = require('browser-window'); // Módulo para crear uan ventana de navegador.
// Reportar crashes a nuestro servidor.
require('crash-reporter').start();
// Mantener una referencia global al objeto window, si no lo haces, esta ventana
// se cerrará automáticamente cuando el objeto JavaScript sea recolectado (garbage collected):
var mainWindow = null;
// Salir de todas las ventanas cuando se cierren.
app.on('window-all-closed', function() {
// En OS X es común que las aplicaciones y su barra de menú
// se mantengan activas hasta que el usuario cierre la aplicación
// explícitamente utilizando Cmd + Q
if (process.platform != 'darwin') {
app.quit();
}
});
// Este método será llamado cuando Electron haya finalizado la inicialización
// y esté listo para crear ventanas de navegador.
app.on('ready', function() {
// Crear la ventana.
mainWindow = new BrowserWindow({width: 800, height: 600});
// cargar el index.html de nuestra aplicación.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// Desplegar devtools.
mainWindow.openDevTools();
// Evento emitido cuando se cierra la ventana.
mainWindow.on('closed', function() {
// Eliminar la referencia del objeto window.
// En el caso de soportar multiples ventanas, es usual almacenar
// los objetos window en un array, este es el momento en el que debes eliminar el elemento correspondiente.
mainWindow = null;
});
});
```
Finalmente el `index.html` es la página web que mostraremos:
```html
<!DOCTYPE html>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using io.js <script>document.write(process.version)</script>
and Electron <script>document.write(process.versions['electron'])</script>.
</body>
</html>
```
## Ejecutar la aplicación
Cuando termines de escribir tu aplicación, puedes distribuirla
siguiendo la [guía de distribución](./application-distribution-es.md)
y luego ejecutar la aplicación empaquetada. También puedes utilizar el binario de Electron
para ejecutar tu aplicación de forma directa.
En Windows:
```bash
$ .\electron\electron.exe your-app\
```
En Linux:
```bash
$ ./electron/electron your-app/
```
En OS X:
```bash
$ ./Electron.app/Contents/MacOS/Electron your-app/
```
`Electron.app` es parte del paquete de release de Electron, puedes descargarlo [aquí](https://github.com/atom/electron/releases).

View file

@ -1,131 +0,0 @@
# クイックスタート
## 導入
ElectronではリッチなネイティブAPIを持ったランタイムを提供することによってピュアなJavaScriptでデスクトップアプリケーションをつくることができます。ウェブサーバーの代わりにデスクトップアプリケーションに焦点をあてたio.jsランタイムであるといえばわかりやすいかもしれません。
ElectronはJavaScriptをGUIライブラリにバインディングしません。その代わりに、ElectronはウェブページをGUIとして使用します。なのでElectronはJavaScriptによってコントロールされる最小のChromiumブラウザでもあるともいえます。
### メインプロセス
Electronでは、`package.json``main`で実行されるプロセスを __メインプロセス__ と呼びます。メインスクリプトではGUIにウェブページを表示することができるプロセスを実行します。
### レンダラープロセス
Electronはウェブページを表示させるためにChromiumを使用しているので、Chromiumのマルチプロセスアーキテクチャが使用されることになります。Electronで実行されるウェブページはそれぞれ自身のプロセスで実行されます。それを __レンダラープロセス__ と呼びます。
通常、ブラウザのウェブページはサウンドボックス環境で実行されネイティブなリソースへのアクセスができません。Electronではウェブページからio.jsのAPIを使って、ネイティブリソースへの権限が与えられます。そのおかげでウェブページの中からJavaScriptを使って低レベルなオペレーティングシステムとのインタラクションが可能になります。
### メインプロセスとリレンダラープロセスの違い
メインプロセスは `BrowserWindow` インスタンスを作ることによってウェブページをつくります。それぞれの `BrowserWindow` インスタンスはそれ自身の リレンダラープロセス上でウェブページを実行します。`BrowserWindow` インスタンスが破棄されると、対応するリレンダラープロセスも終了されます。
メインプロセスはすべてのウェブページとそれに対応するリレンダラープロセスを管理しています。それぞれのリレンダラープロセスは分離しているのでウェブページで実行されていることだけを気に留めておいてください。
ウェブページでは、GUI関連のAPIを呼ぶことはできません。なぜならば、ウェブページで管理しているネイティブのGUIリソースは非常に危険で簡単にリークしてしまうからです。もしウェブページ内でGUIを操作したい場合には、メインプロセスと通信をする必要があります。
Electronでは、メインプロセスとリレンダラープロセスとのコミュニケーションをするために[ipc](../api/ipc-renderer.md)モジュールを提供しています。またそれと、RPC形式の通信を行う[remote](../api/remote.md)モジュールもあります。
## Electronアプリを作成する
一般的に Electronアプリの構成は次のようになります
```text
your-app/
├── package.json
├── main.js
└── index.html
```
`package.json`の形式はNodeモジュールとまったく同じです。 `main` フィールドでアプリを起動するためのスクリプトを特定し、メインプロセスで実行します。 `package.json`の例は次のようになります:
```json
{
"name" : "your-app",
"version" : "0.1.0",
"main" : "main.js"
}
```
`main.js` ではウィンドウを作成してシステムイベントを管理します。典型的な例は次のようになります:
```javascript
var app = require('app'); // Module to control application life.
var BrowserWindow = require('browser-window'); // Module to create native browser window.
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
if (process.platform != 'darwin') {
app.quit();
}
});
// This method will be called when Electron has done everything
// initialization and ready for creating browser windows.
app.on('ready', function() {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// Open the devtools.
mainWindow.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
});
```
最後に表示するウェブページ`index.html`は次のようになります:
```html
<!DOCTYPE html>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using io.js <script>document.write(process.version)</script>
and Electron <script>document.write(process.versions['electron'])</script>.
</body>
</html>
```
## アプリを実行する
アプリケーションを作り終えたら、[Application distribution](./application-distribution.md)ガイドにしたがってディストリビューションを作成します、そしてパッケージされたアプリケーションとして配布することが可能です。またダウンロードしたElectronのバイナリをアプリケーション・ディレクトリを実行するために利用することもできます。
Windowsの場合
```bash
$ .\electron\electron.exe your-app\
```
Linuxの場合
```bash
$ ./electron/electron your-app/
```
OS Xの場合
```bash
$ ./Electron.app/Contents/MacOS/Electron your-app/
```
`Electron.app` はElectronのリリースパッケージに含まれており、[ここ](https://github.com/atom/electron/releases) からダウンロードできます。

View file

@ -1,177 +0,0 @@
# 시작하기
## 소개
Electron은 자바스크립트와 함께 제공되는 풍부한 네이티브 API를 이용하여 데스크톱 어플리케이션을 만들 수 있도록 해주는 프레임워크입니다.
이 프레임워크의 io.js(node.js)는 웹 서버 개발이 아닌 데스크톱 어플리케이션 개발에 초점을 맞췄습니다.
이것은 Electron이 GUI 라이브러리의 자바스크립트 바인딩이라는 뜻이 아닙니다.
대신에, Electron은 웹 페이지의 GUI를 사용합니다. 쉽게 말해 Electron은 자바스크립트를 사용하여 조작하는 작은 Chromium
브라우저로 볼 수 있습니다.
### 메인 프로세스
Electron은 실행될 때 __메인 프로세스__ 로 불리는 `package.json``main` 스크립트를 호출합니다.
이 스크립트는 메인 프로세스에서 작동합니다. GUI 컴포넌트를 컨트롤하거나 웹 페이지 창을 생성할 수 있습니다.
### 랜더러 프로세스
Electron이 웹페이지를 보여줄 때 Chromium의 multi-processes 구조도 같이 사용됩니다.
Electron 프로세스 내에서 작동하는 웹 페이지는 __랜더러 프로세스__ 라고 불립니다.
보통 일반 브라우저의 웹 페이지들은 샌드박스가 적용된 환경에서 작동하며 네이티브 리소스에는 접근할 수 없도록 되어 있습니다.
하지만 Electron은 웹 페이지 내에서 io.js(node.js) API를 사용하여 low-level 수준으로 운영체제와 상호작용할 수 있습니다.
### 메인 프로세스와 랜더러 프로세스의 차이점
메인 프로세스는 `BrowserWindow` Class를 이용하여 창을 만들 수 있습니다. `BrowserWindow` 인스턴스는
따로 분리된 프로세스에서 랜더링 되며 `BrowserWindow` 인스턴스가 소멸할 때 해당하는 랜더러 프로세스도 같이 소멸합니다.
메인 프로세스는 모든 웹 페이지와 그에 해당하는 랜더러 프로세스를 관리하며
랜더러 프로세스는 각각의 프로세스에 고립되며 웹 페이지의 작동에만 영향을 끼칩니다.
웹 페이지 내에서 네이티브 GUI 리소스를 관리하는 것은 보안에 취약하고 리소스를 누수시킬 수 있기 때문에
웹 페이지 내에서는 네이티브 GUI와 관련된 API를 호출할 수 없도록 되어 있습니다.
만약 웹 페이지 내에서 GUI작업이 필요하다면 메인 프로세스에서 그 작업을 할 수 있도록 메인 프로세스와 통신을 해야합니다.
Electron에는 메인 프로세스와 랜더러 프로세스간에 통신을 할 수 있도록 [ipc](../api/ipc-renderer-ko.md) 모듈을 제공하고 있습니다.
또한 [remote](../api/remote-ko.md) 모듈을 사용하여 RPC 스타일로 통신할 수도 있습니다.
## 첫번째 Electron 앱 만들기
보통 Electron 앱은 다음과 같은 폴더 구조를 가집니다:
```text
your-app/
├── package.json
├── main.js
└── index.html
```
`package.json`은 node 모듈의 package.json과 같습니다. 그리고 `main` 필드를 지정하여
메인 프로세스로 사용할 어플리케이션 시작점을 정의할 수 있습니다.
예를 들어 사용할 수 있는 `package.json`은 다음과 같습니다:
```json
{
"name" : "your-app",
"version" : "0.1.0",
"main" : "main.js"
}
```
`main.js`에서 창을 만들거나 시스템 이벤트를 처리할 수 있습니다. 대표적인 예제로 다음과 같이 작성할 수 있습니다:
```javascript
var app = require('app'); // 어플리케이션 기반을 조작 하는 모듈.
var BrowserWindow = require('browser-window'); // 네이티브 브라우저 창을 만드는 모듈.
// Electron 개발자에게 crash-report를 보냄.
require('crash-reporter').start();
// 윈도우 객체를 전역에 유지합니다. 만약 이렇게 하지 않으면
// 자바스크립트 GC가 일어날 때 창이 자동으로 닫혀버립니다.
var mainWindow = null;
// 모든 창이 닫히면 어플리케이션 종료.
app.on('window-all-closed', function() {
// OS X의 대부분의 어플리케이션은 유저가 Cmd + Q 커맨드로 확실하게 종료하기 전까지
// 메뉴바에 남아 계속 실행됩니다.
if (process.platform != 'darwin') {
app.quit();
}
});
// 이 메서드는 Electron의 초기화가 모두 끝나고
// 브라우저 창을 열 준비가 되었을 때 호출됩니다.
app.on('ready', function() {
// 새로운 브라우저 창을 생성합니다.
mainWindow = new BrowserWindow({width: 800, height: 600});
// 그리고 현재 디렉터리의 index.html을 로드합니다.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// 개발자 콘솔을 엽니다.
mainWindow.openDevTools();
// 창이 닫히면 호출됩니다.
mainWindow.on('closed', function() {
// 윈도우 객체의 참조를 삭제합니다 보통 멀티 윈도우 지원을 위해
// 윈도우 객체를 배열에 저장하는 경우가 있는데 이 경우
// 해당하는 모든 윈도우 객체의 참조를 삭제해 주어야 합니다.
mainWindow = null;
});
});
```
마지막으로 사용자에게 보여줄 `index.html` 웹 페이지의 예제입니다:
```html
<!DOCTYPE html>
<html>
<head>
<title>헬로 월드!</title>
</head>
<body>
<h1>헬로 월드!</h1>
이 어플리케이션은 io.js <script>document.write(process.version)</script>
Electron <script>document.write(process.versions['electron'])</script>을 사용합니다.
</body>
</html>
```
## 앱 실행하기
앱을 작성한 후 [어플리케이션 배포](./application-distribution-ko.md) 가이드를 따라 앱을 패키징 하고 패키징한 앱을 실행할 수 있습니다.
또는 Electron 실행파일을 다운로드 받아 바로 실행해 볼 수도 있습니다.
### electron-prebuilt
`npm`을 통해 `electron-prebuilt` 패키지를 전역에 설치하면 간단한 명령으로 앱을 실행해 볼 수 있습니다.
앱 디렉터리 내에서 이렇게 실행합니다:
```bash
electron .
```
또는 앱 디렉터리 밖에서 앱 디렉터리를 입력해도 됩니다:
```bash
electron app
```
npm 모듈을 로컬에 설치했다면 이렇게 실행할 수 있습니다:
```bash
./node_modules/.bin/electron .
```
### 임의로 다운로드 받은 Electron
만약 Electron 바이너리를 임의로 다운로드 받았다면 다음과 같이 앱 디렉터리에 놓고 실행하면 됩니다.
#### Windows
```bash
$ .\electron\electron.exe your-app\
```
#### Linux
```bash
$ ./electron/electron your-app/
```
#### OS X
```bash
$ ./Electron.app/Contents/MacOS/Electron your-app/
```
앱 실행파일은 `Electron`의 release 패키지에 포함되어 있습니다.
[여기](https://github.com/atom/electron/releases)에서 다운로드 받을 수 있습니다.
### 배포용 파일 만들기
모든 앱 작성이 끝났다면 [어플리케이션 배포](./application-distribution-ko.md) 가이드를 보고 본격적으로 제작한 앱을 배포할 수 있습니다.

View file

@ -1,57 +0,0 @@
# Utilizando módulos Node nativos
Los módulos Node nativos son soportados por Electron, pero dado que Electron
está utilizando una versión distinta de V8, debes especificar manualmente la
ubicación de las cabeceras de Electron a la hora de compilar módulos nativos.
## Compatibilidad de módulos nativos
A partir de Node v0.11.x han habido cambios vitales en la API de V8.
Es de esperar que los módulos escritos para Node v0.10.x no funcionen con Node v0.11.x.
Electron utiliza Node v.0.11.13 internamente, y por este motivo tiene el mismo problema.
Para resolver esto, debes usar módulos que soporten Node v0.11.x,
[muchos módulos](https://www.npmjs.org/browse/depended/nan) soportan ambas versiones.
En el caso de los módulos antiguos que sólo soportan Node v0.10.x, debes usar el módulo
[nan](https://github.com/rvagg/nan) para portarlos a v0.11.x.
## ¿Cómo instalar módulos nativos?
### La forma fácil
La forma más sencilla de recompilar módulos nativos es a través del paquete
[`electron-rebuild`](https://github.com/paulcbetts/electron-rebuild),
el cual abstrae y maneja los pasos de descargar las cabeceras y compilar los módulos nativos:
```sh
npm install --save-dev electron-rebuild
# Ejecuta esto cada vez que ejecutes npm install
./node_modules/.bin/electron-rebuild
```
### La forma node-gyp
Para compilar módulos Node con las cabeceras de Electron, debes indicar a `node-gyp`
desde dónde descargar las cabeceras y cuál versión usar:
```bash
$ cd /path-to-module/
$ HOME=~/.electron-gyp node-gyp rebuild --target=0.29.1 --arch=x64 --dist-url=https://atom.io/download/atom-shell
```
Los cambios en `HOME=~/.electron-gyp` fueron para especificar la ruta de las cabeceras.
La opción `--target=0.29.1` es la versión de Electron. La opción `--dist-url=...` especifica
dónde descargar las cabeceras. `--arch=x64` indica que el módulo será compilado para un sistema de 64bit.
### La forma npm
También puedes usar `npm` para instalar módulos, los pasos son exactamente igual a otros módulos Node,
con la excepción de que necesitas establecer algunas variables de entorno primero:
```bash
export npm_config_disturl=https://atom.io/download/atom-shell
export npm_config_target=0.29.1
export npm_config_arch=x64
HOME=~/.electron-gyp npm install module-name
```

View file

@ -1,53 +0,0 @@
# 네이티브 node 모듈 사용하기
__역주: 현재 Electron은 node.js대신 io.js를 사용합니다. 문서에 기재된 버전과 다를 수 있습니다__
Electron에선 node.js 네이티브 모듈이 지원됩니다. 하지만 Electron은 공식 node.js의 V8 엔진과는 달리 다른 V8 버전을 사용합니다.
그런 이유로 네이티브 모듈을 사용하기 위해선 Electron의 V8 버전에 맞춰 네이티브 모듈을 다시 빌드하고 헤더를 변경해야 합니다.
## 네이티브 node 모듈 호환성
Node v0.11.x 버전부터는 V8 API의 중대한 변경이 있었습니다. 하지만 일반적으로 모든 네이티브 모듈은 Node v0.10.x 버전을 타겟으로 작성 되었기 때문에
Node v0.11.x 버전에선 작동하지 않습니다. Electron은 내부적으로 Node v0.11.13 버전을 사용합니다. 그래서 위에서 설명한 문제가 발생합니다.
이 문제를 해결하기 위해 모듈이 Node v0.11.x 버전을 지원할 수 있도록 해야합니다.
현재 [많은 모듈들](https://www.npmjs.org/browse/depended/nan)이 안정적으로 두 버전 모두 지원하고 있지만 오래된 모듈의 경우 Node v0.10.x 버전만을 지원하고 있습니다.
예를 들어 [nan](https://github.com/rvagg/nan) 모듈을 사용해야 하는 경우 Node v0.11.x 버전으로 포팅 할 필요가 있습니다.
## 네이티브 모듈 설치하는 방법
### 쉬운 방법 - 권장
[`electron-rebuild`](https://github.com/paulcbetts/electron-rebuild) 패키지를 사용하면 아주 빠르고 정확하게 네이티브 모듈을 다시 빌드할 수 있습니다.
다음의 간단한 절차를 통해 자동으로 헤더를 다운로드하고 네이티브 모듈을 빌드할 수 있습니다:
```sh
npm install --save-dev electron-rebuild
# 필요한 네이티브 모듈을 `npm install`로 설치한 후 다음 작업을 실행하세요:
./node_modules/.bin/electron-rebuild
```
### node-gyp을 이용한 방법
Node 모듈을 `node-gyp`를 사용하여 Electron을 타겟으로 빌드할 땐 `node-gyp`에 헤더 다운로드 주소와 버전을 알려주어야합니다:
```bash
$ cd /path-to-module/
$ HOME=~/.electron-gyp node-gyp rebuild --target=0.29.1 --arch=x64 --dist-url=https://atom.io/download/atom-shell
```
`HOME=~/.electron-gyp`은 변경할 헤더의 위치를 찾습니다. `--target=0.29.1`은 Electron의 버전입니다.
`--dist-url=...`은 헤더를 다운로드 하는 주소입니다. `--arch=x64`는 64비트 시스템을 타겟으로 빌드 한다는 것을 `node-gyp`에게 알려줍니다.
### npm을 이용한 방법
또한 `npm`을 사용하여 모듈을 설치할 수도 있습니다.
환경변수가 필요한 것을 제외하고는 일반 Node 모듈을 설치하는 방법과 완전히 똑같습니다:
```bash
export npm_config_disturl=https://atom.io/download/atom-shell
export npm_config_target=0.29.1
export npm_config_arch=x64
HOME=~/.electron-gyp npm install module-name
```

View file

@ -1,58 +0,0 @@
# Utilizando el plugin Pepper Flash
El plugin Pepper Flash es soportado ahora. Para utilizar pepper flash en Electron, debes especificar la ubicación del plugin manualmente y activarlo en tu aplicación.
## Preparar una copia del plugin Flash
En OSX y Linux, el detalle del plugin puede encontrarse accediendo a `chrome://plugins` en el navegador. Su ubicación y versión son útiles para el soporte. También puedes copiarlo a otro lugar.
## Agrega la opción a Electron
Puedes agregar la opción `--ppapi-flash-path` y `ppapi-flash-version` o utilizar el método `app.commandLine.appendSwitch` antes del evento ready de la aplicación.
También puedes agregar la opción `plugins` de `browser-window`. Por ejemplo,
```javascript
var app = require('app');
var BrowserWindow = require('browser-window');
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
if (process.platform != 'darwin') {
app.quit();
}
});
// Specify flash path.
// On Windows, it might be /path/to/pepflashplayer.dll
// On Mac, /path/to/PepperFlashPlayer.plugin
// On Linux, /path/to/libpepflashplayer.so
app.commandLine.appendSwitch('ppapi-flash-path', '/path/to/libpepflashplayer.so');
// Specify flash version, for example, v17.0.0.169
app.commandLine.appendSwitch('ppapi-flash-version', '17.0.0.169');
app.on('ready', function() {
mainWindow = new BrowserWindow({
'width': 800,
'height': 600,
'web-preferences': {
'plugins': true
}
});
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// Something else
});
```
## Activar el plugin flash en una etiqueta `<webview>`
Agrega el atributo `plugins`.
```html
<webview src="http://www.adobe.com/software/flash/about/" plugins></webview>
```

View file

@ -1,59 +0,0 @@
# Pepper 플래시 플러그인 사용하기
필요하다면 Pepper 플래시 플러그인을 사용할 수 있습니다. Electron에서 pepper 플래시 플러그인을 사용하기 위해선 따로 pepper 플래시 플러그인의 위치를 지정해 주어야합니다.
## 플래시 플러그인 준비하기
크롬 브라우저의 `chrome://plugins` 페이지에 접속한 후 `세부정보`에서 플래시 플러그인의 위치와 버전을 찾을 수 있습니다.
Electron에서 플래시 플러그인을 지원하기 위해선 이 두 가지를 복사해 와야 합니다.
## Electron 스위치 추가
플러그인을 사용하기 위해 직접적으로 `--ppapi-flash-path``ppapi-flash-version` 플래그를 ready 이벤트가 호출되기 전에 추가해야합니다.
그리고 `browser-window``plugins` 스위치도 추가해야합니다.
```javascript
var app = require('app');
var BrowserWindow = require('browser-window');
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
if (process.platform != 'darwin') {
app.quit();
}
});
// 플래시 플러그인의 위치를 설정합니다.
// Windows의 경우, /path/to/pepflashplayer.dll
// Mac의 경우, /path/to/PepperFlashPlayer.plugin
// Linux의 경우, /path/to/libpepflashplayer.so
app.commandLine.appendSwitch('ppapi-flash-path', '/path/to/libpepflashplayer.so');
// Specify flash version, for example, v17.0.0.169
app.commandLine.appendSwitch('ppapi-flash-version', '17.0.0.169');
app.on('ready', function() {
mainWindow = new BrowserWindow({
'width': 800,
'height': 600,
'web-preferences': {
'plugins': true
}
});
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// Something else
});
```
## `<webview>` 태그를 이용하여 플러그인을 활성화
`plugins` 속성을 `<webview>` 태그에 추가합니다.
```html
<webview src="http://www.adobe.com/software/flash/about/" plugins></webview>
```

View file

@ -1,72 +0,0 @@
# Utilizando Selenium y WebDriver
De [ChromeDriver - WebDriver for Chrome][chrome-driver]:
> WebDriver es una herramienta de código abierto para automatizar el testing de aplicaciones web
> en varios navegadores. WebDriver provee funciones de navegación, entrada de usuario,
> ejecución de JavaScript, y más. ChromeDriver es un servidor standalone que implementa
> el protocolo de WebDriver para Chromium. Se encuentra en desarrollo por los miembros de
> Chromium y WebDriver.
En la página de [lanzamientos](https://github.com/atom/electron/releases) de Electron encontrarás paquetes de `chromedriver`.
## Ajustando parámetros con WebDriverJs
[WebDriverJs](https://code.google.com/p/selenium/wiki/WebDriverJs) provee
un paquete Node para realizar testing con web driver, lo usaremos como ejemplo.
### 1. Inicia chrome driver
Primero necesitas descargar el binario `chromedriver` y ejecutarlo:
```bash
$ ./chromedriver
Starting ChromeDriver (v2.10.291558) on port 9515
Only local connections are allowed.
```
Recuerda el puerto `9515`, lo utilizaremos después.
### 2. Instala WebDriverJS
```bash
$ npm install selenium-webdriver
```
### 3. Conecta chrome driver
El uso de `selenium-webdriver` junto con Electron es básicamente el mismo que el original,
excepto que necesitas especificar manualmente cómo se conectará el chrome driver
y dónde encontrará el binario de Electron:
```javascript
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder()
// El puerto "9515" es que abre chrome driver.
.usingServer('http://localhost:9515')
.withCapabilities({chromeOptions: {
// Aquí especificamos la ruta a Electron
binary: '/Path-to-Your-App.app/Contents/MacOS/Atom'}})
.forBrowser('electron')
.build();
driver.get('http://www.google.com');
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');
driver.findElement(webdriver.By.name('btnG')).click();
driver.wait(function() {
return driver.getTitle().then(function(title) {
return title === 'webdriver - Google Search';
});
}, 1000);
driver.quit();
```
## Workflow
Para probar tu aplicación sin recompilar Electron, simplemente [copia](https://github.com/atom/electron/blob/master/docs/tutorial/application-distribution.md) las fuentes de tu aplicación en el directorio de recursos de Electron.
[chrome-driver]: https://sites.google.com/a/chromium.org/chromedriver/

View file

@ -1,74 +0,0 @@
# Selenium 과 WebDriver 사용하기
[ChromeDriver - WebDriver for Chrome][chrome-driver]로 부터 인용:
> WebDriver는 많은 브라우저에서 웹 앱을 자동적으로 테스트하는 툴입니다.
> 이 툴킷은 웹 페이지를 자동으로 탐색하고 유저 폼을 사용하거나 자바스크립트를 실행하는 등의 작업을 수행할 수 있습니다.
> ChromeDriver는 Chromium의 WebDriver wire 프로토콜 스텐드얼론 서버 구현입니다.
> Chromium 과 WebDriver 팀 멤버에 의해 개발되었습니다.
Electron의 [releases](https://github.com/atom/electron/releases) 페이지에서 `chromedriver` 릴리즈 압축파일을 찾을 수 있습니다.
`chromedriver`의 Electron 배포판과 upstream과의 차이는 없습니다.
`chromedriver`와 Electron을 함께 사용하려면 몇가지 설정이 필요합니다.
또한 releases에는 `chromedriver`를 포함하여 주 버전만 업데이트 됩니다. (예시: `vX.X.0` releases)
왜냐하면 `chromedriver`는 Electron 자체에서 자주 업데이트하지 않기 때문입니다.
## WebDriverJs 설정하기
[WebDriverJs](https://code.google.com/p/selenium/wiki/WebDriverJs)는 WebDriver를 사용하여 테스팅 할 수 있도록 도와주는 node 패키지입니다.
다음 예제를 참고하세요:
### 1. 크롬 드라이버 시작
먼저, `chromedriver` 바이너리를 다운로드 받고 실행합니다:
```bash
$ ./chromedriver
Starting ChromeDriver (v2.10.291558) on port 9515
Only local connections are allowed.
```
곧 사용하므로 포트 `9515`를 기억해 놓습니다.
### 2. WebDriverJS 설치
```bash
$ npm install selenium-webdriver
```
### 3. 크롬 드라이버에 연결
`selenium-webdriver`를 Electron과 같이 사용할 땐 기본적으로 upstream과 같습니다.
한가지 다른점이 있다면 수동으로 크롬 드라이버 연결에 대해 설정하고 Electron 실행파일의 위치를 전달합니다:
```javascript
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder()
// 작동하고 있는 크롬 드라이버의 포트 "9515"를 사용합니다.
.usingServer('http://localhost:9515')
.withCapabilities({chromeOptions: {
// 여기에 사용중인 Electron 바이너리의 경로를 기재하세요.
binary: '/Path-to-Your-App.app/Contents/MacOS/Atom'}})
.forBrowser('electron')
.build();
driver.get('http://www.google.com');
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');
driver.findElement(webdriver.By.name('btnG')).click();
driver.wait(function() {
return driver.getTitle().then(function(title) {
return title === 'webdriver - Google Search';
});
}, 1000);
driver.quit();
```
## 작업환경
따로 Electron을 다시 빌드하지 않는 경우 간단히 어플리케이션을 Electron의 리소스 디렉터리에
[배치](https://github.com/atom/electron/blob/master/docs/tutorial/application-distribution-ko.md)하여 바로 테스트 할 수 있습니다.
[chrome-driver]: https://sites.google.com/a/chromium.org/chromedriver/

View file

@ -70,6 +70,53 @@ driver.wait(function() {
driver.quit();
```
## Setting up with WebdriverIO
[WebdriverIO](http://webdriver.io/) provides a Node package for testing with web driver.
### 1. Start chrome driver
First you need to download the `chromedriver` binary, and run it:
```bash
$ chromedriver --url-base=/wd/hub --port=9515
Starting ChromeDriver (v2.10.291558) on port 9515
Only local connections are allowed.
```
Remember the port number `9515`, which will be used later
### 2. Install WebdriverIO
```bash
$ npm install webdriverio
```
### 3. Connect to chrome driver
```javascript
var webdriverio = require('webdriverio');
var options = {
host: "localhost", // Use localhost as chrome driver server
port: 9515, // "9515" is the port opened by chrome driver.
desiredCapabilities: {
browserName: 'chrome',
chromeOptions: {binary: '/Path-to-Your-App.app/Electron'} // Path to your Electron binary.
}
};
var client = webdriverio.remote(options);
client
.init()
.url('http://google.com')
.setValue('#q', 'webdriverio')
.click('#btnG')
.getTitle().then(function(title) {
console.log('Title was: ' + title);
})
.end();
```
## Workflow
To test your application without rebuilding Electron, simply [place](https://github.com/atom/electron/blob/master/docs/tutorial/application-distribution.md) your app source into Electron's resource directory.