Skip to content

Commit

Permalink
Delint / modernize
Browse files Browse the repository at this point in the history
  • Loading branch information
chbrown committed Jul 10, 2018
1 parent 3f6956e commit 2f90296
Show file tree
Hide file tree
Showing 15 changed files with 77 additions and 92 deletions.
9 changes: 3 additions & 6 deletions PDF.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import chalk from 'chalk';
import {Paper} from 'academia/types';
import {Source} from 'lexing';
import {lastIndexOf} from 'lexing/source';
Expand Down Expand Up @@ -117,10 +116,10 @@ export class PDF {
getModel<T extends models.Model>(object_number: number,
generation_number: number,
ctor: { new(pdf: PDF, object: pdfdom.PDFObject): T }): T {
const model_id = `${ctor['name']}(${object_number}:${generation_number})`;
const model_id = `${ctor.name}(${object_number}:${generation_number})`;
// the type coersion below assumes that the caller read the doc comment
// on this function.
let cached_model = <T>this._cached_models[model_id];
let cached_model = this._cached_models[model_id] as T;
if (cached_model === undefined) {
const object = this.getObject(object_number, generation_number);
cached_model = this._cached_models[model_id] = new ctor(this, object);
Expand Down Expand Up @@ -191,10 +190,8 @@ export class PDF {
This is useful in the PDFObjectParser stream hack, but shouldn't be used elsewhere.
*/
_resolveObject(object: pdfdom.PDFObject): pdfdom.PDFObject {
// type-assertion hack, sry. Why do you make it so difficult, TypeScript?
if (models.IndirectReference.isIndirectReference(object)) {
const reference = <pdfdom.IndirectReference>object;
return this.getObject(reference.object_number, reference.generation_number);
return this.getObject(object.object_number, object.generation_number);
}
return object;
}
Expand Down
4 changes: 2 additions & 2 deletions encoding/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {nfkc} from 'unorm';
import {readCharCodes, swapEndian} from '../util';
import {swapEndian} from '../util';

/**
glyphlist is a mapping from PDF glyph names to unicode strings
Expand Down Expand Up @@ -184,7 +184,7 @@ export function decodeBuffer(buffer: Buffer): string {
return swapEndian(buffer).toString('utf16le');
}
const chunks: string[] = [];
for (var i = 0, l = buffer.length; i < l; i++) {
for (let i = 0, l = buffer.length; i < l; i++) {
chunks.push(PDFDocUnicode[buffer[i]]);
}
return chunks.join('');
Expand Down
2 changes: 1 addition & 1 deletion filters/decoders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ export function ASCIIHexDecode(ascii: List<number>): Buffer {
}

export function FlateDecode(buffer: Buffer, decodeParms: DecodeParms): Buffer {
const inflated = Buffer.from(inflate(<any>buffer));
const inflated = Buffer.from(inflate(buffer as Uint8Array));
if (decodeParms && decodeParms.Predictor && decodeParms.Columns) {
if (decodeParms.Predictor !== 12) {
throw new Error(`Unsupported DecodeParms.Predictor value: "${decodeParms.Predictor}"`);
Expand Down
4 changes: 1 addition & 3 deletions font/descriptor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import {logger} from '../logger';
import {Encoding} from '../encoding/index';
import * as glyphmaps from '../encoding/glyphmaps';
import {Model, ContentStream} from '../models';
import {mergeArray} from '../util';
Expand Down Expand Up @@ -69,7 +67,7 @@ export class FontDescriptor extends Model {
private getType1FontProgramClearText(): string {
const Type1FontProgram = new ContentStream(this._pdf, this.object['FontFile']);
if (Type1FontProgram.object) {
const Length1 = <number>Type1FontProgram.dictionary['Length1'];
const Length1 = Type1FontProgram.dictionary.Length1 as number;
return Type1FontProgram.buffer.toString('ascii', 0, Length1);
}
}
Expand Down
24 changes: 12 additions & 12 deletions font/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {Encoding, expandDifferences, decodeGlyphname} from '../encoding/index';
import glyphlist from '../encoding/glyphlist';
import * as glyphmaps from '../encoding/glyphmaps';
import {logger} from '../logger';
import {PDF, Model, ContentStream, Resources} from '../models';
import {PDF, Model, ContentStream} from '../models';
import {parseCMap} from '../parsers/index';
import {PDFObject} from '../pdfdom';
import {memoize, mergeArray, readCharCodes} from '../util';
Expand Down Expand Up @@ -55,7 +55,7 @@ export abstract class Font extends Model {
return Encoding['BaseEncoding'];
}
if (typeof Encoding == 'string') {
return <string>Encoding;
return Encoding;
}
}

Expand All @@ -73,7 +73,7 @@ export abstract class Font extends Model {
Maybe not always?
*/
get BaseFont(): string {
return <string>this.get('BaseFont');
return this.get('BaseFont') as string;
}

/**
Expand Down Expand Up @@ -374,13 +374,13 @@ export class Type1Font extends Font {
// Try using the local Widths, etc., configuration first.
// TODO: avoid this BaseFont_name hack and resolve TrueType fonts properly
const BaseFont_name = this.BaseFont ? this.BaseFont.split(',')[0] : null;
const Widths = <number[]>new Model(this._pdf, this.get('Widths')).object;
const Widths = new Model(this._pdf, this.get('Widths')).object as number[];
// FontMatrix and multiple should only technically be used for Type3 fonts
const FontMatrix = <number[]>this.get('FontMatrix');
const FontMatrix = this.get('FontMatrix') as number[];
const multiplier = FontMatrix ? (FontMatrix[0] / 0.001) : 1;
// logger.debug(`Font[${this.Name}] Using width multiplier ${multiplier}`);
if (Widths) {
const FirstChar = <number>this.get('FirstChar');
const FirstChar = this.get('FirstChar') as number;
// TODO: verify LastChar?
this._widthMapping = {};
Widths.forEach((width, width_index) => {
Expand Down Expand Up @@ -488,7 +488,7 @@ export class CIDFont extends Model {

get W(): Array<number | number[]> {
const model = new Model(this._pdf, this.object['W']);
return <Array<number | number[]>>model.object;
return model.object as Array<number | number[]>;
}

getDefaultWidth(): number {
Expand Down Expand Up @@ -522,15 +522,15 @@ export class CIDFont extends Model {
const length = cid_widths.length;
while (index < length) {
if (Array.isArray(cid_widths[index + 1])) {
const starting_cid_value = <number>cid_widths[index];
const widths = <number[]>cid_widths[index + 1];
const starting_cid_value = cid_widths[index] as number;
const widths = cid_widths[index + 1] as number[];
addConsecutive(starting_cid_value, widths);
index += 2;
}
else {
const c_first = <number>cid_widths[index];
const c_last = <number>cid_widths[index + 1];
const width = <number>cid_widths[index + 2];
const c_first = cid_widths[index] as number;
const c_last = cid_widths[index + 1] as number;
const width = cid_widths[index + 2] as number;
addRange(c_first, c_last, width);
index += 3;
}
Expand Down
2 changes: 1 addition & 1 deletion graphics/geometry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ export function mat3add(A: Mat3, B: Mat3): Mat3 {
return [
A[0] + B[0], A[1] + B[1], A[2] + B[2],
A[3] + B[3], A[4] + B[4], A[5] + B[5],
A[6] + B[6], A[7] + B[7], A[8] + B[8]
A[6] + B[6], A[7] + B[7], A[8] + B[8],
];
}

Expand Down
9 changes: 4 additions & 5 deletions graphics/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import {Paper} from 'academia/types';
import {assign, flatMap, mean, median, quantile} from 'tarry';
import {flatMap, quantile} from 'tarry';

import {logger} from '../logger';
import {Page, ContentStream, Resources} from '../models';
import {normalize} from '../encoding/index';
import {Multiset, unwrapLines} from '../util';

import {
transformPoint,
Rectangle, makeRectangle, distanceToRectangle, formatRectangle, boundingRectangle,
Container, makeContainer, addElements, mergeContainer,
Rectangle, makeRectangle,
Container,
} from './geometry';
import {groupLines, groupColumns, partitionWords, splitParagraphs} from './layout';
import {TextAtom, TextAtomDrawingContext} from './stream';
Expand Down Expand Up @@ -58,7 +57,7 @@ export function renderLayout(outerBounds: Rectangle,
({minX, minY, maxX, maxY, elements: partitionWords(elements)}));
const columns = groupColumns(lineContainers);
// columns -> paragraphs is a reconfiguration of containers, not a nesting as the others are
const paragraphs = flatMap(columns, column => splitParagraphs(column));
const paragraphs = flatMap(columns, splitParagraphs);
return paragraphs;
}

Expand Down
6 changes: 3 additions & 3 deletions graphics/layout.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {flatMap, mean, median, quantile} from 'tarry';
import {median} from 'tarry';

import {
Rectangle, distanceToRectangle, formatRectangle, boundingRectangle,
Container, makeContainer, addElements, mergeContainer,
Rectangle, distanceToRectangle,
Container, makeContainer, addElements,
} from './geometry';

/**
Expand Down
35 changes: 17 additions & 18 deletions graphics/stream.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import chalk from 'chalk';

import {logger} from '../logger';
import {Font} from '../font/index';
import {Resources} from '../models';
import {clone, checkArguments} from '../util';
import {parseContentStream, ContentStreamOperation} from '../parsers/index';
import {clone} from '../util';
import {parseContentStream} from '../parsers/index';

import {Point, transformPoint, Size, Rectangle, formatRectangle, Mat3, mat3mul, mat3ident} from './geometry';
import {Point, Size, Mat3, mat3mul, mat3ident} from './geometry';

export class Color {
clone(): Color { return new Color(); }
Expand Down Expand Up @@ -160,7 +159,7 @@ export abstract class DrawingContext {
// width_units is positive, but we want to move forward, so tx should be positive too
const tx = (((width_units / 1000) * fontSize) + (charSpacing * chars) + (wordSpacing * spaces)) *
(horizontalScaling / 100.0);
const [a, b,, c, d,, e, f] = this.textMatrix;
const [a, b, , c, d, , e, f] = this.textMatrix;
this.textMatrix = [a, b, 0, c, d, 0, tx * a + e, tx * b + f, 1];
return tx;
}
Expand Down Expand Up @@ -376,7 +375,7 @@ export abstract class DrawingContext {
`h`
*/
closePath() {
logger.debug(`Ignoring closePath() operation`);
logger.debug('Ignoring closePath() operation');
}
/**
> `x y width height re`: Append a rectangle to the current path as a complete
Expand All @@ -396,7 +395,7 @@ export abstract class DrawingContext {
> `S`: Stroke the path.
*/
stroke() {
logger.debug(`Ignoring stroke() operation`);
logger.debug('Ignoring stroke() operation');
}
/** ALIAS
> `s`: Close and stroke the path. This operator shall have the same effect as the sequence h S.
Expand All @@ -410,7 +409,7 @@ export abstract class DrawingContext {
*/
fill() {
// this.closePath(); ?
logger.debug(`Ignoring fill() operation`);
logger.debug('Ignoring fill() operation');
}
/** ALIAS
> `F`: Equivalent to f; included only for compatibility. Although PDF reader applications shall be able to accept this operator, PDF writer applications should use f instead.
Expand All @@ -422,20 +421,20 @@ export abstract class DrawingContext {
> `f*`: Fill the path, using the even-odd rule to determine the region to fill.
*/
fillEvenOdd() {
logger.debug(`Ignoring fillEvenOdd() operation`);
logger.debug('Ignoring fillEvenOdd() operation');
}
/**
> `B`: Fill and then stroke the path, using the nonzero winding number rule to determine the region to fill. This operator shall produce the same result as constructing two identical path objects, painting the first with f and the second with S.
> NOTE The filling and stroking portions of the operation consult different values of several graphics state parameters, such as the current colour.
*/
fillThenStroke() {
logger.debug(`Ignoring fillAndStroke() operation`);
logger.debug('Ignoring fillAndStroke() operation');
}
/**
> `B*`: Fill and then stroke the path, using the even-odd rule to determine the region to fill. This operator shall produce the same result as B, except that the path is filled as if with f* instead of f.
*/
fillThenStrokeEvenOdd() {
logger.debug(`Ignoring fillAndStrokeEvenOdd() operation`);
logger.debug('Ignoring fillAndStrokeEvenOdd() operation');
}
/** ALIAS
> `b`: Close, fill, and then stroke the path, using the nonzero winding number rule to determine the region to fill. This operator shall have the same effect as the sequence h B.
Expand All @@ -455,7 +454,7 @@ export abstract class DrawingContext {
> `n`: End the path object without filling or stroking it. This operator shall be a path- painting no-op, used primarily for the side effect of changing the current clipping path.
*/
closePathNoop() {
logger.debug(`Ignoring closePathNoop() operation`);
logger.debug('Ignoring closePathNoop() operation');
}
// ---------------------------------------------------------------------------
// Color operators
Expand Down Expand Up @@ -546,24 +545,24 @@ export abstract class DrawingContext {
// ---------------------------------------------------------------------------
// Inline Image Operators (BI, ID, EI)
beginInlineImage() {
logger.debug(`Ignoring beginInlineImage() operation`);
logger.debug('Ignoring beginInlineImage() operation');
}
endInlineImage(...args: any[]) {
logger.debug(`Ignoring endInlineImage() operation`);
logger.debug('Ignoring endInlineImage() operation');
}
// ---------------------------------------------------------------------------
// Clipping Path Operators (W, W*)
/**
> `W`: Modify the current clipping path by intersecting it with the current path, using the nonzero winding number rule to determine which regions lie inside the clipping path.
*/
clip() {
logger.debug(`Ignoring clip() operation`);
logger.debug('Ignoring clip() operation');
}
/**
> `W*`: Modify the current clipping path by intersecting it with the current path, using the even-odd rule to determine which regions lie inside the clipping path.
*/
clipEvenOdd() {
logger.debug(`Ignoring clipEvenOdd() operation`);
logger.debug('Ignoring clipEvenOdd() operation');
}
// ---------------------------------------------------------------------------
// Text objects (BT, ET)
Expand Down Expand Up @@ -644,7 +643,7 @@ export abstract class DrawingContext {
*/
adjustCurrentPosition(x: number, y: number) {
// y is usually 0, and never positive in normal text.
const [a, b,, c, d,, e, f] = this.textLineMatrix;
const [a, b, , c, d, , e, f] = this.textLineMatrix;
this.textMatrix = this.textLineMatrix = [a, b, 0,
c, d, 0,
(x * a) + (y * c) + e, (x * b) + (y * d) + f, 1];
Expand Down Expand Up @@ -771,7 +770,7 @@ export abstract class DrawingContext {
> `EMC`: End a marked-content sequence begun by a BMC or BDC operator.
*/
endMarkedContent() {
logger.debug(`Ignoring endMarkedContent() operation`);
logger.debug('Ignoring endMarkedContent() operation');
}
}

Expand Down
6 changes: 3 additions & 3 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {tuplesToObject} from 'tarry';

import {logger, Level} from './logger';
import {PDF} from './PDF';
import {IndirectReference, Model, ContentStream} from './models';
import {Model} from './models';
import {decodeBuffer} from './encoding/index';

export function setLoggerLevel(level: Level) {
Expand Down Expand Up @@ -63,7 +63,7 @@ export function simplify(value: any, seen: any[] = []): any {
return value;
}
else if (value instanceof Model) {
const object = (<Model>value).object;
const object = value.object;
return simplify(object, seen);
}
else if (Buffer.isBuffer(value)) {
Expand All @@ -85,7 +85,7 @@ export function simplify(value: any, seen: any[] = []): any {
}
seen.push(value);
// maybe something less function, more loopy, with a hasOwnProperty check?
return tuplesToObject(<any>Object.keys(value).map(key => ([key, simplify(value[key], seen)])));
return tuplesToObject(Object.keys(value).map(key => ([key, simplify(value[key], seen)] as [string, any])));
}
// catch-all
return value;
Expand Down
6 changes: 2 additions & 4 deletions models.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import {BufferIterator} from 'lexing';
import {asArray, flatMap, groups, assign} from 'tarry';

import {logger} from './logger';
import {PDFBufferIterator} from './parsers/index';
import {OBJECT} from './parsers/states';
import {IndirectObject, PDFObject, Rectangle, DictionaryObject} from './pdfdom';
Expand All @@ -26,9 +24,9 @@ where the object's Type indicates useful ways it may be processed.
export class IndirectReference {
constructor(public object_number: number, public generation_number: number) { }

static isIndirectReference(object): boolean {
static isIndirectReference(object: any): object is IndirectReference {
if (object === undefined || object === null) return false;
return (object['object_number'] !== undefined) && (object['generation_number'] !== undefined);
return (object.object_number !== undefined) && (object.generation_number !== undefined);
}
/**
Create an IndirectReference from an "object[:reference=0]" string.
Expand Down
6 changes: 1 addition & 5 deletions parsers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,12 @@ import {

import {logger} from '../logger';
import {
OBJECT,
STARTXREF,
XREF_WITH_TRAILER,
CONTENT_STREAM,
CMAP,
ContentStreamOperation,
CMap,
} from './states';
import {PDF} from '../models';
import {PDFObject, IndirectObject} from '../pdfdom';

import {MachineStateConstructor} from './machine';

Expand Down Expand Up @@ -70,7 +66,7 @@ export function parseStateAt<T, I>(source: Source,
return new STATE(iterable, encoding, peekLength).read();
}
catch (exc) {
logger.error(`Error trying to parse ${STATE['name']}: ${chalk.red(exc.message)}`);
logger.error(`Error trying to parse ${STATE.name}: ${chalk.red(exc.message)}`);
printContext(source, position, iterable.position);

throw exc;
Expand Down
Loading

0 comments on commit 2f90296

Please sign in to comment.