FlatCAMApp.py 263 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import re
  17. import os
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import tkinter as tk
  21. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  22. import time # Just used for debugging. Double check before removing.
  23. import urllib.request, urllib.parse, urllib.error
  24. import webbrowser
  25. from contextlib import contextmanager
  26. from xml.dom.minidom import parseString as parse_xml_string
  27. from copy import copy,deepcopy
  28. import numpy as np
  29. from datetime import datetime
  30. import gc
  31. ########################################
  32. ## Imports part of FlatCAM ##
  33. ########################################
  34. from ObjectCollection import *
  35. from FlatCAMObj import *
  36. from PlotCanvas import *
  37. from FlatCAMGUI import *
  38. from FlatCAMCommon import LoudDict
  39. from FlatCAMPostProc import load_postprocessors
  40. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  41. from FlatCAMProcess import *
  42. from FlatCAMWorkerStack import WorkerStack
  43. from VisPyVisuals import Color
  44. from vispy.gloo.util import _screenshot
  45. from vispy.io import write_png
  46. from flatcamTools import *
  47. from multiprocessing import Pool
  48. import tclCommands
  49. # from ParseFont import *
  50. ########################################
  51. ## App ##
  52. ########################################
  53. class App(QtCore.QObject):
  54. """
  55. The main application class. The constructor starts the GUI.
  56. """
  57. # Get Cmd Line Options
  58. cmd_line_shellfile = ''
  59. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  60. try:
  61. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  62. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  63. except getopt.GetoptError:
  64. print(cmd_line_help)
  65. sys.exit(2)
  66. for opt, arg in cmd_line_options:
  67. if opt == '-h':
  68. print(cmd_line_help)
  69. sys.exit()
  70. elif opt == '--shellfile':
  71. cmd_line_shellfile = arg
  72. # Logging ##
  73. log = logging.getLogger('base')
  74. log.setLevel(logging.DEBUG)
  75. # log.setLevel(logging.WARNING)
  76. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  77. handler = logging.StreamHandler()
  78. handler.setFormatter(formatter)
  79. log.addHandler(handler)
  80. # Version
  81. version = 8.906
  82. version_date = "2019/02/1"
  83. beta = True
  84. # URL for update checks and statistics
  85. version_url = "http://flatcam.org/version"
  86. # App URL
  87. app_url = "http://flatcam.org"
  88. # Manual URL
  89. manual_url = "http://flatcam.org/manual/index.html"
  90. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  91. should_we_quit = True
  92. ##################
  93. ## Signals ##
  94. ##################
  95. # Inform the user
  96. # Handled by:
  97. # * App.info() --> Print on the status bar
  98. inform = QtCore.pyqtSignal(str)
  99. # General purpose background task
  100. worker_task = QtCore.pyqtSignal(dict)
  101. # File opened
  102. # Handled by:
  103. # * register_folder()
  104. # * register_recent()
  105. # Note: Setting the parameters to unicode does not seem
  106. # to have an effect. Then are received as Qstring
  107. # anyway.
  108. # File type and filename
  109. file_opened = QtCore.pyqtSignal(str, str)
  110. # File type and filename
  111. file_saved = QtCore.pyqtSignal(str, str)
  112. # Percentage of progress
  113. progress = QtCore.pyqtSignal(int)
  114. plots_updated = QtCore.pyqtSignal()
  115. # Emitted by new_object() and passes the new object as argument, plot flag.
  116. # on_object_created() adds the object to the collection, plots on appropriate flag
  117. # and emits new_object_available.
  118. object_created = QtCore.pyqtSignal(object, bool, bool)
  119. # Emitted when a object has been changed (like scaled, mirrored)
  120. object_changed = QtCore.pyqtSignal(object)
  121. # Emitted after object has been plotted.
  122. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  123. object_plotted = QtCore.pyqtSignal(object)
  124. # Emitted when a new object has been added to the collection
  125. # and is ready to be used.
  126. new_object_available = QtCore.pyqtSignal(object)
  127. message = QtCore.pyqtSignal(str, str, str)
  128. # Emmited when shell command is finished(one command only)
  129. shell_command_finished = QtCore.pyqtSignal(object)
  130. # Emitted when multiprocess pool has been recreated
  131. pool_recreated = QtCore.pyqtSignal(object)
  132. # Emitted when an unhandled exception happens
  133. # in the worker task.
  134. thread_exception = QtCore.pyqtSignal(object)
  135. def __init__(self, user_defaults=True, post_gui=None):
  136. """
  137. Starts the application.
  138. :return: app
  139. :rtype: App
  140. """
  141. App.log.info("FlatCAM Starting...")
  142. ###################
  143. ### OS-specific ###
  144. ###################
  145. # Folder for user settings.
  146. if sys.platform == 'win32':
  147. from win32com.shell import shell, shellcon
  148. if platform.architecture()[0] == '32bit':
  149. App.log.debug("Win32!")
  150. else:
  151. App.log.debug("Win64!")
  152. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  153. '\FlatCAM'
  154. self.os = 'windows'
  155. else: # Linux/Unix/MacOS
  156. self.data_path = os.path.expanduser('~') + \
  157. '/.FlatCAM'
  158. self.os = 'unix'
  159. ###############################
  160. ### Setup folders and files ###
  161. ###############################
  162. if not os.path.exists(self.data_path):
  163. os.makedirs(self.data_path)
  164. App.log.debug('Created data folder: ' + self.data_path)
  165. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  166. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  167. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  168. if not os.path.exists(self.postprocessorpaths):
  169. os.makedirs(self.postprocessorpaths)
  170. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  171. # create current_defaults.FlatConfig file if there is none
  172. try:
  173. f = open(self.data_path + '/current_defaults.FlatConfig')
  174. f.close()
  175. except IOError:
  176. App.log.debug('Creating empty current_defaults.FlatConfig')
  177. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  178. json.dump({}, f)
  179. f.close()
  180. # create factory_defaults.FlatConfig file if there is none
  181. try:
  182. f = open(self.data_path + '/factory_defaults.FlatConfig')
  183. f.close()
  184. except IOError:
  185. App.log.debug('Creating empty factory_defaults.FlatConfig')
  186. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  187. json.dump({}, f)
  188. f.close()
  189. try:
  190. f = open(self.data_path + '/recent.json')
  191. f.close()
  192. except IOError:
  193. App.log.debug('Creating empty recent.json')
  194. f = open(self.data_path + '/recent.json', 'w')
  195. json.dump([], f)
  196. f.close()
  197. # Application directory. CHDIR to it. Otherwise, trying to load
  198. # GUI icons will fail as their path is relative.
  199. # This will fail under cx_freeze ...
  200. self.app_home = os.path.dirname(os.path.realpath(__file__))
  201. App.log.debug("Application path is " + self.app_home)
  202. App.log.debug("Started in " + os.getcwd())
  203. # cx_freeze workaround
  204. if os.path.isfile(self.app_home):
  205. self.app_home = os.path.dirname(self.app_home)
  206. os.chdir(self.app_home)
  207. # Create multiprocessing pool
  208. self.pool = Pool()
  209. ####################
  210. ## Initialize GUI ##
  211. ####################
  212. # FlatCAM colors used in plotting
  213. self.FC_light_green = '#BBF268BF'
  214. self.FC_dark_green = '#006E20BF'
  215. self.FC_light_blue = '#a5a5ffbf'
  216. self.FC_dark_blue = '#0000ffbf'
  217. QtCore.QObject.__init__(self)
  218. self.ui = FlatCAMGUI(self.version, self.beta, self)
  219. # self.connect(self.ui,
  220. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  221. # self.save_geometry) PyQt4
  222. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  223. self.ui.final_save.connect(self.final_save)
  224. ##############
  225. #### Data ####
  226. ##############
  227. self.recent = []
  228. self.clipboard = QtWidgets.QApplication.clipboard()
  229. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  230. self.project_filename = None
  231. self.toggle_units_ignore = False
  232. # self.defaults_form = PreferencesUI()
  233. self.general_defaults_form = GeneralPreferencesUI()
  234. self.gerber_defaults_form = GerberPreferencesUI()
  235. self.excellon_defaults_form = ExcellonPreferencesUI()
  236. self.geometry_defaults_form = GeometryPreferencesUI()
  237. self.cncjob_defaults_form = CNCJobPreferencesUI()
  238. self.tools_defaults_form = ToolsPreferencesUI()
  239. # when adding entries here read the comments in the method found bellow named:
  240. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  241. self.defaults_form_fields = {
  242. "units": self.general_defaults_form.general_app_group.units_radio,
  243. "global_shell_at_startup": self.general_defaults_form.general_app_group.shell_startup_cb,
  244. "global_version_check": self.general_defaults_form.general_app_group.version_check_cb,
  245. "global_send_stats": self.general_defaults_form.general_app_group.send_stats_cb,
  246. "global_gridx": self.general_defaults_form.general_gui_group.gridx_entry,
  247. "global_gridy": self.general_defaults_form.general_gui_group.gridy_entry,
  248. "global_plot_fill": self.general_defaults_form.general_gui_group.pf_color_entry,
  249. "global_plot_line": self.general_defaults_form.general_gui_group.pl_color_entry,
  250. "global_sel_fill": self.general_defaults_form.general_gui_group.sf_color_entry,
  251. "global_sel_line": self.general_defaults_form.general_gui_group.sl_color_entry,
  252. "global_alt_sel_fill": self.general_defaults_form.general_gui_group.alt_sf_color_entry,
  253. "global_alt_sel_line": self.general_defaults_form.general_gui_group.alt_sl_color_entry,
  254. "global_draw_color": self.general_defaults_form.general_gui_group.draw_color_entry,
  255. "global_sel_draw_color": self.general_defaults_form.general_gui_group.sel_draw_color_entry,
  256. "global_pan_button": self.general_defaults_form.general_app_group.pan_button_radio,
  257. "global_mselect_key": self.general_defaults_form.general_app_group.mselect_radio,
  258. # "global_pan_with_space_key": self.general_defaults_form.general_gui_group.pan_with_space_cb,
  259. "global_workspace": self.general_defaults_form.general_gui_group.workspace_cb,
  260. "global_workspaceT": self.general_defaults_form.general_gui_group.wk_cb,
  261. "global_theme": self.general_defaults_form.general_gui_group.theme_combo,
  262. "gerber_plot": self.gerber_defaults_form.gerber_gen_group.plot_cb,
  263. "gerber_solid": self.gerber_defaults_form.gerber_gen_group.solid_cb,
  264. "gerber_multicolored": self.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  265. "gerber_circle_steps": self.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  266. "gerber_isotooldia": self.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  267. "gerber_isopasses": self.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  268. "gerber_isooverlap": self.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  269. "gerber_combine_passes": self.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  270. "gerber_milling_type": self.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  271. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  272. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  273. "gerber_bboxmargin": self.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  274. "gerber_bboxrounded": self.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  275. "excellon_plot": self.excellon_defaults_form.excellon_gen_group.plot_cb,
  276. "excellon_solid": self.excellon_defaults_form.excellon_gen_group.solid_cb,
  277. "excellon_format_upper_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  278. "excellon_format_lower_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  279. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  280. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  281. "excellon_zeros": self.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  282. "excellon_units": self.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  283. "excellon_optimization_type": self.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  284. "excellon_search_time": self.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  285. "excellon_drillz": self.excellon_defaults_form.excellon_opt_group.cutz_entry,
  286. "excellon_travelz": self.excellon_defaults_form.excellon_opt_group.travelz_entry,
  287. "excellon_feedrate": self.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  288. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_opt_group.feedrate_rapid_entry,
  289. "excellon_spindlespeed": self.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  290. "excellon_dwell": self.excellon_defaults_form.excellon_opt_group.dwell_cb,
  291. "excellon_dwelltime": self.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  292. "excellon_toolchange": self.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  293. "excellon_toolchangez": self.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  294. "excellon_toolchangexy": self.excellon_defaults_form.excellon_opt_group.toolchangexy_entry,
  295. "excellon_ppname_e": self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  296. "excellon_f_plunge": self.excellon_defaults_form.excellon_opt_group.fplunge_cb,
  297. "excellon_startz": self.excellon_defaults_form.excellon_opt_group.estartz_entry,
  298. "excellon_endz": self.excellon_defaults_form.excellon_opt_group.eendz_entry,
  299. "excellon_tooldia": self.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  300. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  301. "excellon_gcode_type": self.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  302. "geometry_plot": self.geometry_defaults_form.geometry_gen_group.plot_cb,
  303. "geometry_cnctooldia": self.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  304. "geometry_circle_steps": self.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  305. "geometry_segx": self.geometry_defaults_form.geometry_opt_group.segx_entry,
  306. "geometry_segy": self.geometry_defaults_form.geometry_opt_group.segy_entry,
  307. "geometry_cutz": self.geometry_defaults_form.geometry_opt_group.cutz_entry,
  308. "geometry_travelz": self.geometry_defaults_form.geometry_opt_group.travelz_entry,
  309. "geometry_feedrate": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  310. "geometry_feedrate_z": self.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  311. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_rapid_entry,
  312. "geometry_spindlespeed": self.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  313. "geometry_dwell": self.geometry_defaults_form.geometry_opt_group.dwell_cb,
  314. "geometry_dwelltime": self.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  315. "geometry_ppname_g": self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  316. "geometry_f_plunge": self.geometry_defaults_form.geometry_opt_group.fplunge_cb,
  317. "geometry_toolchange": self.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  318. "geometry_toolchangez": self.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  319. "geometry_toolchangexy": self.geometry_defaults_form.geometry_opt_group.toolchangexy_entry,
  320. "geometry_startz": self.geometry_defaults_form.geometry_opt_group.gstartz_entry,
  321. "geometry_endz": self.geometry_defaults_form.geometry_opt_group.gendz_entry,
  322. "geometry_multidepth": self.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  323. "geometry_depthperpass": self.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  324. "geometry_extracut": self.geometry_defaults_form.geometry_opt_group.extracut_cb,
  325. "cncjob_plot": self.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  326. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  327. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  328. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  329. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  330. "cncjob_prepend": self.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  331. "cncjob_append": self.cncjob_defaults_form.cncjob_opt_group.append_text,
  332. "tools_ncctools": self.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  333. "tools_nccoverlap": self.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  334. "tools_nccmargin": self.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  335. "tools_nccmethod": self.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  336. "tools_nccconnect": self.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  337. "tools_ncccontour": self.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  338. "tools_nccrest": self.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  339. "tools_cutouttooldia": self.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  340. "tools_cutoutmargin": self.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  341. "tools_cutoutgapsize": self.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  342. "tools_gaps_rect": self.tools_defaults_form.tools_cutout_group.gaps_radio,
  343. "tools_gaps_ff": self.tools_defaults_form.tools_cutout_group.gaps_combo,
  344. "tools_painttooldia": self.tools_defaults_form.tools_paint_group.painttooldia_entry,
  345. "tools_paintoverlap": self.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  346. "tools_paintmargin": self.tools_defaults_form.tools_paint_group.paintmargin_entry,
  347. "tools_paintmethod": self.tools_defaults_form.tools_paint_group.paintmethod_combo,
  348. "tools_selectmethod": self.tools_defaults_form.tools_paint_group.selectmethod_combo,
  349. "tools_pathconnect": self.tools_defaults_form.tools_paint_group.pathconnect_cb,
  350. "tools_paintcontour": self.tools_defaults_form.tools_paint_group.contour_cb,
  351. "tools_2sided_mirror_axis": self.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  352. "tools_2sided_axis_loc": self.tools_defaults_form.tools_2sided_group.axis_location_radio,
  353. "tools_2sided_drilldia": self.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  354. }
  355. # loads postprocessors
  356. self.postprocessors = load_postprocessors(self)
  357. for name in list(self.postprocessors.keys()):
  358. self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  359. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  360. if name == 'hpgl':
  361. continue
  362. self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  363. self.defaults = LoudDict()
  364. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  365. self.defaults.update({
  366. "global_serial": 0,
  367. "global_stats": {},
  368. "units": "IN",
  369. "global_version_check": True,
  370. "global_send_stats": True,
  371. "global_gridx": 1.0,
  372. "global_gridy": 1.0,
  373. "global_plot_fill": '#BBF268BF',
  374. "global_plot_line": '#006E20BF',
  375. "global_sel_fill": '#a5a5ffbf',
  376. "global_sel_line": '#0000ffbf',
  377. "global_alt_sel_fill": '#BBF268BF',
  378. "global_alt_sel_line": '#006E20BF',
  379. "global_draw_color": '#FF0000',
  380. "global_sel_draw_color": '#0000FF',
  381. "global_pan_button": '2',
  382. "global_mselect_key": 'Control',
  383. # "global_pan_with_space_key": False,
  384. "global_workspace": False,
  385. "global_workspaceT": "A4P",
  386. "global_toolbar_view": 31,
  387. "global_background_timeout": 300000, # Default value is 5 minutes
  388. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  389. # (python trace only for unknown errors),
  390. # 1 = show trace(show trace allways),
  391. # 2 = (For the future).
  392. # Persistence
  393. "global_last_folder": None,
  394. "global_last_save_folder": None,
  395. # Default window geometry
  396. "global_def_win_x": 100,
  397. "global_def_win_y": 100,
  398. "global_def_win_w": 1024,
  399. "global_def_win_h": 650,
  400. "global_theme": 'standard',
  401. # Constants...
  402. "global_defaults_save_period_ms": 20000, # Time between default saves.
  403. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  404. "global_shell_at_startup": False, # Show the shell at startup.
  405. "global_recent_limit": 10, # Max. items in recent list.
  406. "fit_key": '1',
  407. "zoom_out_key": '2',
  408. "zoom_in_key": '3',
  409. "grid_toggle_key": 'G',
  410. "zoom_ratio": 1.5,
  411. "global_point_clipboard_format": "(%.4f, %.4f)",
  412. "global_zdownrate": None,
  413. "gerber_plot": True,
  414. "gerber_solid": True,
  415. "gerber_multicolored": False,
  416. "gerber_isotooldia": 0.016,
  417. "gerber_isopasses": 1,
  418. "gerber_isooverlap": 0.15,
  419. "gerber_combine_passes": False,
  420. "gerber_milling_type": "cl",
  421. "gerber_noncoppermargin": 0.1,
  422. "gerber_noncopperrounded": False,
  423. "gerber_bboxmargin": 0.1,
  424. "gerber_bboxrounded": False,
  425. "gerber_circle_steps": 64,
  426. "gerber_use_buffer_for_union": True,
  427. "excellon_plot": True,
  428. "excellon_solid": True,
  429. "excellon_format_upper_in": 2,
  430. "excellon_format_lower_in": 4,
  431. "excellon_format_upper_mm": 3,
  432. "excellon_format_lower_mm": 3,
  433. "excellon_zeros": "L",
  434. "excellon_units": "INCH",
  435. "excellon_optimization_type": 'B',
  436. "excellon_search_time": 3,
  437. "excellon_drillz": -0.1,
  438. "excellon_travelz": 0.1,
  439. "excellon_feedrate": 3.0,
  440. "excellon_feedrate_rapid": 3.0,
  441. "excellon_spindlespeed": None,
  442. "excellon_dwell": False,
  443. "excellon_dwelltime": 1,
  444. "excellon_toolchange": False,
  445. "excellon_toolchangez": 1.0,
  446. "excellon_toolchangexy": "0.0, 0.0",
  447. "excellon_tooldia": 0.016,
  448. "excellon_slot_tooldia": 0.016,
  449. "excellon_startz": None,
  450. "excellon_endz": 2.0,
  451. "excellon_ppname_e": 'default',
  452. "excellon_f_plunge": False,
  453. "excellon_gcode_type": "drills",
  454. "geometry_plot": True,
  455. "geometry_segx": 0.0,
  456. "geometry_segy": 0.0,
  457. "geometry_cutz": -0.002,
  458. "geometry_travelz": 0.1,
  459. "geometry_toolchange": False,
  460. "geometry_toolchangez": 1.0,
  461. "geometry_toolchangexy": "0.0, 0.0",
  462. "geometry_startz": None,
  463. "geometry_endz": 2.0,
  464. "geometry_feedrate": 3.0,
  465. "geometry_feedrate_z": 3.0,
  466. "geometry_feedrate_rapid": 3.0,
  467. "geometry_cnctooldia": 0.016,
  468. "geometry_spindlespeed": None,
  469. "geometry_dwell": False,
  470. "geometry_dwelltime": 1,
  471. "geometry_ppname_g": 'default',
  472. "geometry_f_plunge": False,
  473. "geometry_depthperpass": 0.002,
  474. "geometry_multidepth": False,
  475. "geometry_extracut": False,
  476. "geometry_circle_steps": 64,
  477. "cncjob_plot": True,
  478. "cncjob_tooldia": 0.0393701,
  479. "cncjob_coords_decimals": 4,
  480. "cncjob_fr_decimals": 2,
  481. "cncjob_prepend": "",
  482. "cncjob_append": "",
  483. "cncjob_steps_per_circle": 64,
  484. "tools_ncctools": "1.0, 0.5",
  485. "tools_nccoverlap": 0.4,
  486. "tools_nccmargin": 0.1,
  487. "tools_nccmethod": "seed",
  488. "tools_nccconnect": True,
  489. "tools_ncccontour": True,
  490. "tools_nccrest": False,
  491. "tools_cutouttooldia": 0.1,
  492. "tools_cutoutmargin": 0.1,
  493. "tools_cutoutgapsize": 0.15,
  494. "tools_gaps_rect": "4",
  495. "tools_gaps_ff": "8",
  496. "tools_painttooldia": 0.07,
  497. "tools_paintoverlap": 0.15,
  498. "tools_paintmargin": 0.0,
  499. "tools_paintmethod": "seed",
  500. "tools_selectmethod": "single",
  501. "tools_pathconnect": True,
  502. "tools_paintcontour": True,
  503. "tools_2sided_mirror_axis": "X",
  504. "tools_2sided_axis_loc": "point",
  505. "tools_2sided_drilldia": 1,
  506. })
  507. ###############################
  508. ### Load defaults from file ###
  509. if user_defaults:
  510. self.load_defaults(filename='current_defaults')
  511. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  512. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  513. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  514. self.save_defaults(silent=True)
  515. self.propagate_defaults(silent=True)
  516. self.restore_main_win_geom()
  517. def auto_save_defaults():
  518. try:
  519. self.save_defaults(silent=True)
  520. self.propagate_defaults(silent=True)
  521. finally:
  522. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  523. # the following lines activates automatic defaults save
  524. # if user_defaults:
  525. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  526. # self.options_form = PreferencesUI()
  527. self.general_options_form = GeneralPreferencesUI()
  528. self.gerber_options_form = GerberPreferencesUI()
  529. self.excellon_options_form = ExcellonPreferencesUI()
  530. self.geometry_options_form = GeometryPreferencesUI()
  531. self.cncjob_options_form = CNCJobPreferencesUI()
  532. self.tools_options_form = ToolsPreferencesUI()
  533. self.options_form_fields = {
  534. "units": self.general_options_form.general_app_group.units_radio,
  535. "global_gridx": self.general_options_form.general_gui_group.gridx_entry,
  536. "global_gridy": self.general_options_form.general_gui_group.gridy_entry,
  537. "global_theme": self.general_options_form.general_gui_group.theme_combo,
  538. "gerber_plot": self.gerber_options_form.gerber_gen_group.plot_cb,
  539. "gerber_solid": self.gerber_options_form.gerber_gen_group.solid_cb,
  540. "gerber_multicolored": self.gerber_options_form.gerber_gen_group.multicolored_cb,
  541. "gerber_isotooldia": self.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  542. "gerber_isopasses": self.gerber_options_form.gerber_opt_group.iso_width_entry,
  543. "gerber_isooverlap": self.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  544. "gerber_combine_passes": self.gerber_options_form.gerber_opt_group.combine_passes_cb,
  545. "gerber_noncoppermargin": self.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  546. "gerber_noncopperrounded": self.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  547. "gerber_bboxmargin": self.gerber_options_form.gerber_opt_group.bbmargin_entry,
  548. "gerber_bboxrounded": self.gerber_options_form.gerber_opt_group.bbrounded_cb,
  549. "excellon_plot": self.excellon_options_form.excellon_gen_group.plot_cb,
  550. "excellon_solid": self.excellon_options_form.excellon_gen_group.solid_cb,
  551. "excellon_format_upper_in": self.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  552. "excellon_format_lower_in": self.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  553. "excellon_format_upper_mm": self.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  554. "excellon_format_lower_mm": self.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  555. "excellon_zeros": self.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  556. "excellon_units": self.excellon_options_form.excellon_gen_group.excellon_units_radio,
  557. "excellon_optimization_type": self.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  558. "excellon_drillz": self.excellon_options_form.excellon_opt_group.cutz_entry,
  559. "excellon_travelz": self.excellon_options_form.excellon_opt_group.travelz_entry,
  560. "excellon_feedrate": self.excellon_options_form.excellon_opt_group.feedrate_entry,
  561. "excellon_feedrate_rapid": self.excellon_options_form.excellon_opt_group.feedrate_rapid_entry,
  562. "excellon_spindlespeed": self.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  563. "excellon_dwell": self.excellon_options_form.excellon_opt_group.dwell_cb,
  564. "excellon_dwelltime": self.excellon_options_form.excellon_opt_group.dwelltime_entry,
  565. "excellon_toolchange": self.excellon_options_form.excellon_opt_group.toolchange_cb,
  566. "excellon_toolchangez": self.excellon_options_form.excellon_opt_group.toolchangez_entry,
  567. "excellon_toolchangexy": self.excellon_options_form.excellon_opt_group.toolchangexy_entry,
  568. "excellon_tooldia": self.excellon_options_form.excellon_opt_group.tooldia_entry,
  569. "excellon_ppname_e": self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  570. "excellon_f_plunge": self.excellon_options_form.excellon_opt_group.fplunge_cb,
  571. "excellon_startz": self.excellon_options_form.excellon_opt_group.estartz_entry,
  572. "excellon_endz": self.excellon_options_form.excellon_opt_group.eendz_entry,
  573. "geometry_plot": self.geometry_options_form.geometry_gen_group.plot_cb,
  574. "geometry_cnctooldia": self.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  575. "geometry_segx": self.geometry_options_form.geometry_opt_group.segx_entry,
  576. "geometry_segy": self.geometry_options_form.geometry_opt_group.segy_entry,
  577. "geometry_cutz": self.geometry_options_form.geometry_opt_group.cutz_entry,
  578. "geometry_travelz": self.geometry_options_form.geometry_opt_group.travelz_entry,
  579. "geometry_feedrate": self.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  580. "geometry_feedrate_z": self.geometry_options_form.geometry_opt_group.cncplunge_entry,
  581. "geometry_feedrate_rapid": self.geometry_options_form.geometry_opt_group.cncfeedrate_rapid_entry,
  582. "geometry_spindlespeed": self.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  583. "geometry_dwell": self.geometry_options_form.geometry_opt_group.dwell_cb,
  584. "geometry_dwelltime": self.geometry_options_form.geometry_opt_group.dwelltime_entry,
  585. "geometry_ppname_g": self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  586. "geometry_f_plunge": self.geometry_options_form.geometry_opt_group.fplunge_cb,
  587. "geometry_toolchange": self.geometry_options_form.geometry_opt_group.toolchange_cb,
  588. "geometry_toolchangez": self.geometry_options_form.geometry_opt_group.toolchangez_entry,
  589. "geometry_toolchangexy": self.geometry_options_form.geometry_opt_group.toolchangexy_entry,
  590. "geometry_startz": self.geometry_options_form.geometry_opt_group.gstartz_entry,
  591. "geometry_endz": self.geometry_options_form.geometry_opt_group.gendz_entry,
  592. "geometry_depthperpass": self.geometry_options_form.geometry_opt_group.depthperpass_entry,
  593. "geometry_multidepth": self.geometry_options_form.geometry_opt_group.multidepth_cb,
  594. "geometry_extracut": self.geometry_options_form.geometry_opt_group.extracut_cb,
  595. "cncjob_plot": self.cncjob_options_form.cncjob_gen_group.plot_cb,
  596. "cncjob_tooldia": self.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  597. "cncjob_prepend": self.cncjob_options_form.cncjob_opt_group.prepend_text,
  598. "cncjob_append": self.cncjob_options_form.cncjob_opt_group.append_text,
  599. "tools_ncctools": self.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  600. "tools_nccoverlap": self.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  601. "tools_nccmargin": self.tools_options_form.tools_ncc_group.ncc_margin_entry,
  602. "tools_cutouttooldia": self.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  603. "tools_cutoutmargin": self.tools_options_form.tools_cutout_group.cutout_margin_entry,
  604. "tools_cutoutgapsize": self.tools_options_form.tools_cutout_group.cutout_gap_entry,
  605. "tools_gaps_rect": self.tools_options_form.tools_cutout_group.gaps_radio,
  606. "tools_gaps_ff": self.tools_options_form.tools_cutout_group.gaps_combo,
  607. "tools_painttooldia": self.tools_options_form.tools_paint_group.painttooldia_entry,
  608. "tools_paintoverlap": self.tools_options_form.tools_paint_group.paintoverlap_entry,
  609. "tools_paintmargin": self.tools_options_form.tools_paint_group.paintmargin_entry,
  610. "tools_paintmethod": self.tools_options_form.tools_paint_group.paintmethod_combo,
  611. "tools_selectmethod": self.tools_options_form.tools_paint_group.selectmethod_combo,
  612. "tools_pathconnect": self.tools_options_form.tools_paint_group.pathconnect_cb,
  613. "tools_paintcontour": self.tools_options_form.tools_paint_group.contour_cb,
  614. "tools_2sided_mirror_axis": self.tools_options_form.tools_2sided_group.mirror_axis_radio,
  615. "tools_2sided_axis_loc": self.tools_options_form.tools_2sided_group.axis_location_radio,
  616. "tools_2sided_drilldia": self.tools_options_form.tools_2sided_group.drill_dia_entry
  617. }
  618. for name in list(self.postprocessors.keys()):
  619. self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  620. self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  621. self.options = LoudDict()
  622. self.options.set_change_callback(self.on_options_dict_change)
  623. self.options.update({
  624. "units": "IN",
  625. "global_gridx": 1.0,
  626. "global_gridy": 1.0,
  627. "global_background_timeout": 300000, # Default value is 5 minutes
  628. "global_verbose_error_level": 0, # Shell verbosity:
  629. # 0 = default(python trace only for unknown errors),
  630. # 1 = show trace(show trace allways), 2 = (For the future).
  631. "global_theme": 'standard',
  632. "gerber_plot": True,
  633. "gerber_solid": True,
  634. "gerber_multicolored": False,
  635. "gerber_isotooldia": 0.016,
  636. "gerber_isopasses": 1,
  637. "gerber_isooverlap": 0.15,
  638. "gerber_combine_passes": True,
  639. "gerber_noncoppermargin": 0.0,
  640. "gerber_noncopperrounded": False,
  641. "gerber_bboxmargin": 0.0,
  642. "gerber_bboxrounded": False,
  643. "excellon_plot": True,
  644. "excellon_solid": False,
  645. "excellon_format_upper_in": 2,
  646. "excellon_format_lower_in": 4,
  647. "excellon_format_upper_mm": 3,
  648. "excellon_format_lower_mm": 3,
  649. "excellon_units": 'INCH',
  650. "excellon_optimization_type": 'B',
  651. "excellon_search_time": 3,
  652. "excellon_zeros": "L",
  653. "excellon_drillz": -0.1,
  654. "excellon_travelz": 0.1,
  655. "excellon_feedrate": 3.0,
  656. "excellon_feedrate_rapid": 3.0,
  657. "excellon_spindlespeed": None,
  658. "excellon_dwell": True,
  659. "excellon_dwelltime": 1000,
  660. "excellon_toolchange": False,
  661. "excellon_toolchangez": 1.0,
  662. "excellon_toolchangexy": "0.0, 0.0",
  663. "excellon_tooldia": 0.016,
  664. "excellon_ppname_e": 'default',
  665. "excellon_f_plunge": False,
  666. "excellon_startz": None,
  667. "excellon_endz": 2.0,
  668. "geometry_plot": True,
  669. "geometry_segx": 0.0,
  670. "geometry_segy": 0.0,
  671. "geometry_cutz": -0.002,
  672. "geometry_travelz": 0.1,
  673. "geometry_feedrate": 3.0,
  674. "geometry_feedrate_z": 3.0,
  675. "geometry_feedrate_rapid": 3.0,
  676. "geometry_spindlespeed": None,
  677. "geometry_dwell": True,
  678. "geometry_dwelltime": 1000,
  679. "geometry_cnctooldia": 0.016,
  680. "geometry_toolchange": False,
  681. "geometry_toolchangez": 2.0,
  682. "geometry_toolchangexy": "0.0, 0.0",
  683. "geometry_startz": None,
  684. "geometry_endz": 2.0,
  685. "geometry_ppname_g": "default",
  686. "geometry_f_plunge": False,
  687. "geometry_depthperpass": 0.002,
  688. "geometry_multidepth": False,
  689. "geometry_extracut": False,
  690. "cncjob_plot": True,
  691. "cncjob_tooldia": 0.016,
  692. "cncjob_prepend": "",
  693. "cncjob_append": "",
  694. "tools_ncctools": "1.0, 0.5",
  695. "tools_nccoverlap": 0.4,
  696. "tools_nccmargin": 1,
  697. "tools_cutouttooldia": 0.07,
  698. "tools_cutoutmargin": 0.1,
  699. "tools_cutoutgapsize": 0.15,
  700. "tools_gaps_rect": "4",
  701. "tools_gaps_ff": "8",
  702. "tools_painttooldia": 0.07,
  703. "tools_paintoverlap": 0.15,
  704. "tools_paintmargin": 0.0,
  705. "tools_paintmethod": "seed",
  706. "tools_selectmethod": "single",
  707. "tools_pathconnect": True,
  708. "tools_paintcontour": True,
  709. "tools_2sided_mirror_axis": "X",
  710. "tools_2sided_axis_loc": 'point',
  711. "tools_2sided_drilldia": 1
  712. })
  713. self.options.update(self.defaults) # Copy app defaults to project options
  714. self.gen_form = None
  715. self.ger_form = None
  716. self.exc_form = None
  717. self.geo_form = None
  718. self.cnc_form = None
  719. self.tools_form = None
  720. self.on_options_combo_change(0) # Will show the initial form
  721. ### Define OBJECT COLLECTION ###
  722. self.collection = ObjectCollection(self)
  723. self.ui.project_tab_layout.addWidget(self.collection.view)
  724. ###
  725. self.log.debug("Finished creating Object Collection.")
  726. ### Initialize the color box's color in Preferences -> Global -> Color
  727. # Init Plot Colors
  728. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  729. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  730. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  731. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  732. int(self.defaults['global_plot_fill'][7:9], 16))
  733. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  734. int(self.defaults['global_plot_fill'][7:9], 16))
  735. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  736. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  737. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  738. # Init Left-Right Selection colors
  739. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  740. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  741. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  742. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  743. int(self.defaults['global_sel_fill'][7:9], 16))
  744. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  745. int(self.defaults['global_sel_fill'][7:9], 16))
  746. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  747. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  748. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  749. # Init Right-Left Selection colors
  750. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  751. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  752. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  753. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  754. int(self.defaults['global_sel_fill'][7:9], 16))
  755. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  756. int(self.defaults['global_sel_fill'][7:9], 16))
  757. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  758. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  759. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  760. # Init Draw color and Selection Draw Color
  761. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  762. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  763. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  764. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  765. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  766. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  767. #### End of Data ####
  768. #### Plot Area ####
  769. start_plot_time = time.time() # debug
  770. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  771. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  772. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  773. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  774. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  775. # Keys over plot enabled
  776. self.plotcanvas.vis_connect('key_press', self.on_key_over_plot)
  777. self.plotcanvas.vis_connect('key_release', self.on_key_release_over_plot)
  778. self.ui.splitter.setStretchFactor(1, 2)
  779. # So it can receive key presses
  780. self.plotcanvas.vispy_canvas.native.setFocus()
  781. self.app_cursor = self.plotcanvas.new_cursor()
  782. self.app_cursor.enabled = False
  783. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  784. # depending on from where those tools are called different actions can be done
  785. self.call_source = 'app'
  786. end_plot_time = time.time()
  787. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  788. ### EDITOR section
  789. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  790. self.exc_editor = FlatCAMExcEditor(self)
  791. # start with GRID activated
  792. self.ui.grid_snap_btn.trigger()
  793. self.ui.corner_snap_btn.setVisible(False)
  794. self.ui.snap_magnet.setVisible(False)
  795. self.ui.g_editor_cmenu.setEnabled(False)
  796. self.ui.e_editor_cmenu.setEnabled(False)
  797. #### Adjust tabs width ####
  798. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  799. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  800. self.collection.view.setMinimumWidth(290)
  801. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  802. #### Worker ####
  803. self.workers = WorkerStack()
  804. self.worker_task.connect(self.workers.add_task)
  805. ### Signal handling ###
  806. ## Custom signals
  807. self.inform.connect(self.info)
  808. self.message.connect(self.message_dialog)
  809. self.progress.connect(self.set_progress_bar)
  810. self.object_created.connect(self.on_object_created)
  811. self.object_changed.connect(self.on_object_changed)
  812. self.object_plotted.connect(self.on_object_plotted)
  813. self.plots_updated.connect(self.on_plots_updated)
  814. self.file_opened.connect(self.register_recent)
  815. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  816. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  817. ## Standard signals
  818. # Menu
  819. self.ui.menufilenew.triggered.connect(self.on_file_new_click)
  820. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  821. self.ui.menufileopengerber_follow.triggered.connect(self.on_fileopengerber_follow)
  822. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  823. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  824. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  825. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  826. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  827. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  828. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  829. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  830. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  831. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  832. self.ui.menufileexportexcellon.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=None))
  833. self.ui.menufileexportexcellon_altium.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=True))
  834. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  835. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  836. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  837. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  838. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  839. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  840. self.ui.menueditnew.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  841. self.ui.menueditnewexc.triggered.connect(self.new_excellon_object)
  842. self.ui.menueditedit.triggered.connect(self.object2editor)
  843. self.ui.menueditok.triggered.connect(self.editor2object)
  844. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  845. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  846. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  847. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  848. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  849. self.ui.menueditdelete.triggered.connect(self.on_delete)
  850. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  851. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  852. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  853. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  854. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  855. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  856. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  857. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  858. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  859. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  860. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  861. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  862. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  863. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  864. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  865. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  866. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  867. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  868. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  869. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  870. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  871. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  872. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  873. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  874. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  875. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  876. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  877. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  878. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  879. self.ui.menuhelp_about.triggered.connect(self.on_about)
  880. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  881. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  882. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  883. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  884. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  885. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  886. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  887. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  888. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  889. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  890. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  891. # Toolbar
  892. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  893. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  894. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  895. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  896. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  897. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  898. self.ui.replot_btn.triggered.connect(self.plot_all)
  899. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  900. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  901. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  902. self.ui.newgeo_btn.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  903. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  904. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  905. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  906. self.ui.delete_btn.triggered.connect(self.on_delete)
  907. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  908. # Context Menu
  909. self.ui.popmenu_new_geo.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  910. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  911. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  912. self.ui.gridmenu_1.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.05"))
  913. self.ui.gridmenu_2.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.1"))
  914. self.ui.gridmenu_3.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.2"))
  915. self.ui.gridmenu_4.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.5"))
  916. self.ui.gridmenu_5.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("1.0"))
  917. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  918. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  919. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  920. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  921. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  922. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  923. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  924. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  925. self.ui.clearplot.triggered.connect(self.clear_plots)
  926. self.ui.replot.triggered.connect(self.plot_all)
  927. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  928. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  929. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  930. self.ui.popmenu_save.triggered.connect(self.editor2object)
  931. self.ui.popmenu_move.triggered.connect(self.obj_move)
  932. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  933. # Preferences Plot Area TAB
  934. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  935. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  936. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  937. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  938. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  939. ###############################
  940. ### GUI PREFERENCES SIGNALS ###
  941. ###############################
  942. self.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  943. self.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(self.on_language_apply)
  944. ###############################
  945. ### GUI PREFERENCES SIGNALS ###
  946. ###############################
  947. # Setting plot colors signals
  948. self.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  949. self.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  950. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  951. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  952. self.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  953. self.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  954. # Setting selection (left - right) colors signals
  955. self.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  956. self.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  957. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  958. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  959. self.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  960. self.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  961. # Setting selection (right - left) colors signals
  962. self.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  963. self.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  964. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  965. self.on_alt_sf_color_spinner)
  966. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  967. self.on_alt_sf_color_slider)
  968. self.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  969. self.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  970. # Setting Editor Draw colors signals
  971. self.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  972. self.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  973. self.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  974. self.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  975. self.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  976. self.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  977. self.general_defaults_form.general_gui_group.theme_combo.currentIndexChanged.connect(self.on_theme)
  978. # Modify G-CODE Plot Area TAB
  979. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  980. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  981. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  982. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  983. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  984. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  985. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  986. # Object list
  987. self.collection.view.activated.connect(self.on_row_activated)
  988. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  989. self.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  990. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  991. self.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  992. self.on_excellon_defaults_button)
  993. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  994. self.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  995. self.on_excellon_options_button)
  996. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  997. self.tool_tab_locked = False
  998. ####################
  999. ### Other setups ###
  1000. ####################
  1001. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1002. self.setup_obj_classes()
  1003. self.setup_recent_items()
  1004. self.setup_component_editor()
  1005. #############
  1006. ### Shell ###
  1007. #############
  1008. ###
  1009. # Auto-complete KEYWORDS
  1010. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1011. 'aligndrill', 'clear',
  1012. 'aligndrillgrid', 'cncjob', 'cutout', 'cutout_any', 'delete', 'drillcncjob',
  1013. 'export_gcode',
  1014. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1015. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1016. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1017. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1018. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1019. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1020. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1021. ]
  1022. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1023. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1024. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1025. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1026. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1027. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1028. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1029. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1030. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1031. ]
  1032. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1033. self.shell = FCShell(self, version=self.version)
  1034. self.shell._edit.set_model_data(self.myKeywords)
  1035. self.shell.setWindowIcon(self.ui.app_icon)
  1036. self.shell.setWindowTitle("FlatCAM Shell")
  1037. self.shell.resize(*self.defaults["global_shell_shape"])
  1038. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1039. self.shell.append_output("(Type help to get started)\n\n")
  1040. self.init_tcl()
  1041. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1042. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1043. self.ui.shell_dock.setWidget(self.shell)
  1044. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1045. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1046. QtWidgets.QDockWidget.DockWidgetFloatable |
  1047. QtWidgets.QDockWidget.DockWidgetClosable)
  1048. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1049. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1050. if self.defaults["global_shell_at_startup"]:
  1051. self.ui.shell_dock.show()
  1052. else:
  1053. self.ui.shell_dock.hide()
  1054. #########################
  1055. ### Tools and Plugins ###
  1056. #########################
  1057. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1058. self.install_tools()
  1059. ### System Font Parsing ###
  1060. # self.f_parse = ParseFont(self)
  1061. # self.parse_system_fonts()
  1062. # test if the program was started with a script as parameter
  1063. if self.cmd_line_shellfile:
  1064. try:
  1065. with open(self.cmd_line_shellfile, "r") as myfile:
  1066. cmd_line_shellfile_text = myfile.read()
  1067. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1068. except Exception as ext:
  1069. print("ERROR: ", ext)
  1070. sys.exit(2)
  1071. ###########################
  1072. #### Check for updates ####
  1073. ###########################
  1074. # Separate thread (Not worker)
  1075. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1076. if (self.beta is False or self.beta is None) and \
  1077. self.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1078. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1079. self.thr2 = QtCore.QThread()
  1080. self.worker_task.emit({'fcn': self.version_check,
  1081. 'params': []})
  1082. self.thr2.start()
  1083. ####################################
  1084. #### Variables for global usage ####
  1085. ####################################
  1086. # coordinates for relative position display
  1087. self.rel_point1 = (0, 0)
  1088. self.rel_point2 = (0, 0)
  1089. # variable to store coordinates
  1090. self.pos = (0, 0)
  1091. self.pos_jump = (0, 0)
  1092. # variable to store if there was motion before right mouse button click (panning)
  1093. self.panning_action = False
  1094. # variable to store if a command is active (then the var is not None) and which one it is
  1095. self.command_active = None
  1096. # variable to store the status of moving selection action
  1097. # None value means that it's not an selection action
  1098. # True value = a selection from left to right
  1099. # False value = a selection from right to left
  1100. self.selection_type = None
  1101. # List to store the objects that are currently loaded in FlatCAM
  1102. # This list is updated on each object creation or object delete
  1103. self.all_objects_list = []
  1104. # List to store the objects that are selected
  1105. self.sel_objects_list = []
  1106. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1107. self.key_modifiers = None
  1108. # Variable to hold the status of the axis
  1109. self.toggle_axis = True
  1110. # Variable to store the status of the fullscreen event
  1111. self.toggle_fscreen = False
  1112. self.cursor = None
  1113. # Variable to store the GCODE that was edited
  1114. self.gcode_edited = ""
  1115. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1116. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1117. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1118. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1119. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1120. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1121. 'mpf']
  1122. self.svg_list = ['svg']
  1123. self.dxf_list = ['dxf']
  1124. self.prj_list = ['flatprj']
  1125. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1126. # flag for polygons not cleared
  1127. self.poly_not_cleared = False
  1128. ### Save defaults to factory_defaults.FlatConfig file ###
  1129. ### It's done only once after install #############
  1130. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1131. fac_def_from_file = factory_file.read()
  1132. factory_defaults = json.loads(fac_def_from_file)
  1133. # if the file contain an empty dictionary then save the factory defaults into the file
  1134. if not factory_defaults:
  1135. self.save_factory_defaults(silent=False)
  1136. factory_file.close()
  1137. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1138. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1139. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1140. # Post-GUI initialization: Experimental attempt
  1141. # to perform unit tests on the GUI.
  1142. # if post_gui is not None:
  1143. # post_gui(self)
  1144. App.log.debug("END of constructor. Releasing control.")
  1145. # accept a project file as command line parameter
  1146. # the path/file_name must be enclosed in quotes if it contain spaces
  1147. for argument in App.args:
  1148. if '.FlatPrj' in argument:
  1149. try:
  1150. project_name = str(argument)
  1151. if project_name == "":
  1152. self.inform.emit("Open cancelled.")
  1153. else:
  1154. # self.open_project(project_name)
  1155. run_from_arg = True
  1156. self.worker_task.emit({'fcn': self.open_project,
  1157. 'params': [project_name, run_from_arg]})
  1158. except Exception as e:
  1159. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1160. def defaults_read_form(self):
  1161. for option in self.defaults_form_fields:
  1162. try:
  1163. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1164. except:
  1165. pass
  1166. def defaults_write_form(self):
  1167. for option in self.defaults:
  1168. self.defaults_write_form_field(option)
  1169. # try:
  1170. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1171. # except KeyError:
  1172. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1173. # # TODO: Rethink this?
  1174. # pass
  1175. def defaults_write_form_field(self, field):
  1176. try:
  1177. self.defaults_form_fields[field].set_value(self.defaults[field])
  1178. except KeyError:
  1179. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1180. # TODO: Rethink this?
  1181. pass
  1182. def clear_pool(self):
  1183. self.pool.close()
  1184. self.pool = Pool()
  1185. self.pool_recreated.emit(self.pool)
  1186. gc.collect()
  1187. # the order that the tools are installed is important as they can depend on each other install position
  1188. def install_tools(self):
  1189. self.dblsidedtool = DblSidedTool(self)
  1190. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1191. self.measurement_tool = Measurement(self)
  1192. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1193. self.panelize_tool = Panelize(self)
  1194. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1195. self.film_tool = Film(self)
  1196. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'), separator=True)
  1197. self.move_tool = ToolMove(self)
  1198. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1199. before=self.ui.menueditorigin)
  1200. self.cutout_tool = ToolCutout(self)
  1201. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1202. before=self.measurement_tool.menuAction)
  1203. self.ncclear_tool = NonCopperClear(self)
  1204. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1205. before=self.measurement_tool.menuAction, separator=True)
  1206. self.paint_tool = ToolPaint(self)
  1207. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1208. before=self.measurement_tool.menuAction, separator=True)
  1209. self.calculator_tool = ToolCalculator(self)
  1210. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1211. self.transform_tool = ToolTransform(self)
  1212. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1213. self.properties_tool = Properties(self)
  1214. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1215. self.image_tool = ToolImage(self)
  1216. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1217. separator=True)
  1218. self.log.debug("Tools are installed.")
  1219. def init_tools(self):
  1220. # delete the data currently in the Tools Tab and the Tab itself
  1221. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1222. if widget is not None:
  1223. widget.deleteLater()
  1224. self.ui.notebook.removeTab(2)
  1225. # rebuild the Tools Tab
  1226. self.ui.tool_tab = QtWidgets.QWidget()
  1227. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1228. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1229. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1230. self.ui.tool_scroll_area = VerticalScrollArea()
  1231. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1232. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1233. self.install_tools()
  1234. self.log.debug("Tools are initialized.")
  1235. # def parse_system_fonts(self):
  1236. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1237. # 'params': []})
  1238. def object2editor(self):
  1239. """
  1240. Send the current Geometry or Excellon object (if any) into the editor.
  1241. :return: None
  1242. """
  1243. # adjust the visibility of some of the canvas context menu
  1244. self.ui.popmenu_edit.setVisible(False)
  1245. self.ui.popmenu_save.setVisible(True)
  1246. if isinstance(self.collection.get_active(), FlatCAMGeometry):
  1247. edited_object = self.collection.get_active()
  1248. # for now, if the Geometry is MultiGeo do not allow the editing
  1249. if edited_object.multigeo is True:
  1250. self.inform.emit("[warning_notcl]Editing a MultiGeo Geometry is not possible for the moment.")
  1251. return
  1252. self.ui.update_obj_btn.setEnabled(True)
  1253. self.geo_editor.edit_fcgeometry(edited_object)
  1254. self.ui.g_editor_cmenu.setEnabled(True)
  1255. # set call source to the Editor we go into
  1256. self.call_source = 'geo_editor'
  1257. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  1258. sel_tab_widget_list = self.ui.selected_tab.findChildren(QtWidgets.QWidget)
  1259. for w in sel_tab_widget_list:
  1260. w.setEnabled(False)
  1261. elif isinstance(self.collection.get_active(), FlatCAMExcellon):
  1262. self.ui.update_obj_btn.setEnabled(True)
  1263. self.exc_editor.edit_exc_obj(self.collection.get_active())
  1264. self.ui.e_editor_cmenu.setEnabled(True)
  1265. # set call source to the Editor we go into
  1266. self.call_source = 'exc_editor'
  1267. else:
  1268. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to edit.")
  1269. return
  1270. # make sure that we can't select another object while in Editor Mode:
  1271. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1272. # delete any selection shape that might be active as they are not relevant in Editor
  1273. self.delete_selection_shape()
  1274. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1275. self.inform.emit("[warning_notcl]Editor is activated ...")
  1276. def editor2object(self):
  1277. """
  1278. Transfers the Geometry or Excellon from the editor to the current object.
  1279. :return: None
  1280. """
  1281. # adjust the visibility of some of the canvas context menu
  1282. self.ui.popmenu_edit.setVisible(True)
  1283. self.ui.popmenu_save.setVisible(False)
  1284. edited_obj = self.collection.get_active()
  1285. obj_type = ""
  1286. if isinstance(edited_obj, FlatCAMGeometry):
  1287. obj_type = "Geometry"
  1288. self.geo_editor.update_fcgeometry(edited_obj)
  1289. self.geo_editor.update_options(edited_obj)
  1290. self.geo_editor.deactivate()
  1291. # edited_obj.on_tool_delete(all=True)
  1292. # edited_obj.on_tool_add(dia=edited_obj.options['cnctooldia'])
  1293. self.ui.corner_snap_btn.setEnabled(False)
  1294. self.ui.update_obj_btn.setEnabled(False)
  1295. self.ui.g_editor_cmenu.setEnabled(False)
  1296. self.ui.e_editor_cmenu.setEnabled(False)
  1297. # update the geo object options so it is including the bounding box values
  1298. try:
  1299. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1300. edited_obj.options['xmin'] = xmin
  1301. edited_obj.options['ymin'] = ymin
  1302. edited_obj.options['xmax'] = xmax
  1303. edited_obj.options['ymax'] = ymax
  1304. except AttributeError:
  1305. self.inform.emit("[warning] Object empty after edit.")
  1306. elif isinstance(edited_obj, FlatCAMExcellon):
  1307. obj_type = "Excellon"
  1308. self.exc_editor.update_exc_obj(edited_obj)
  1309. self.exc_editor.deactivate()
  1310. self.ui.corner_snap_btn.setEnabled(False)
  1311. self.ui.update_obj_btn.setEnabled(False)
  1312. self.ui.g_editor_cmenu.setEnabled(False)
  1313. self.ui.e_editor_cmenu.setEnabled(False)
  1314. else:
  1315. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to update.")
  1316. return
  1317. # restore the call_source to app
  1318. self.call_source = 'app'
  1319. edited_obj.plot()
  1320. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1321. self.inform.emit("[success] %s is updated, returning to App..." % obj_type)
  1322. # reset the Object UI to original settings
  1323. # edited_obj.set_ui(edited_obj.ui_type())
  1324. # edited_obj.build_ui()
  1325. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1326. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1327. def get_last_folder(self):
  1328. return self.defaults["global_last_folder"]
  1329. def get_last_save_folder(self):
  1330. return self.defaults["global_last_save_folder"]
  1331. def report_usage(self, resource):
  1332. """
  1333. Increments usage counter for the given resource
  1334. in self.defaults['global_stats'].
  1335. :param resource: Name of the resource.
  1336. :return: None
  1337. """
  1338. if resource in self.defaults['global_stats']:
  1339. self.defaults['global_stats'][resource] += 1
  1340. else:
  1341. self.defaults['global_stats'][resource] = 1
  1342. def init_tcl(self):
  1343. if hasattr(self,'tcl'):
  1344. # self.tcl = None
  1345. # TODO we need to clean non default variables and procedures here
  1346. # new object cannot be used here as it will not remember values created for next passes,
  1347. # because tcl was execudted in old instance of TCL
  1348. pass
  1349. else:
  1350. self.tcl = tk.Tcl()
  1351. self.setup_shell()
  1352. self.log.debug("TCL Shell has been initialized.")
  1353. # TODO: This shouldn't be here.
  1354. class TclErrorException(Exception):
  1355. """
  1356. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1357. """
  1358. pass
  1359. def shell_message(self, msg, show=False, error=False):
  1360. """
  1361. Shows a message on the FlatCAM Shell
  1362. :param msg: Message to display.
  1363. :param show: Opens the shell.
  1364. :param error: Shows the message as an error.
  1365. :return: None
  1366. """
  1367. if show:
  1368. self.ui.shell_dock.show()
  1369. try:
  1370. if error:
  1371. self.shell.append_error(msg + "\n")
  1372. else:
  1373. self.shell.append_output(msg + "\n")
  1374. except AttributeError:
  1375. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1376. def raise_tcl_unknown_error(self, unknownException):
  1377. """
  1378. Raise exception if is different type than TclErrorException
  1379. this is here mainly to show unknown errors inside TCL shell console.
  1380. :param unknownException:
  1381. :return:
  1382. """
  1383. if not isinstance(unknownException, self.TclErrorException):
  1384. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1385. else:
  1386. raise unknownException
  1387. def display_tcl_error(self, error, error_info=None):
  1388. """
  1389. escape bracket [ with \ otherwise there is error
  1390. "ERROR: missing close-bracket" instead of real error
  1391. :param error: it may be text or exception
  1392. :return: None
  1393. """
  1394. if isinstance(error, Exception):
  1395. exc_type, exc_value, exc_traceback = error_info
  1396. if not isinstance(error, self.TclErrorException):
  1397. show_trace = 1
  1398. else:
  1399. show_trace = int(self.defaults['global_verbose_error_level'])
  1400. if show_trace > 0:
  1401. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1402. trc_formated = []
  1403. for a in reversed(trc):
  1404. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1405. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1406. exc_type,
  1407. "\n".join(trc_formated))
  1408. else:
  1409. text = "%s" % error
  1410. else:
  1411. text = error
  1412. text = text.replace('[', '\\[').replace('"', '\\"')
  1413. self.tcl.eval('return -code error "%s"' % text)
  1414. def raise_tcl_error(self, text):
  1415. """
  1416. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1417. :param text: text of error
  1418. :return: raise exception
  1419. """
  1420. self.display_tcl_error(text)
  1421. raise self.TclErrorException(text)
  1422. def exec_command(self, text):
  1423. """
  1424. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1425. Also handles execution in separated threads
  1426. :param text:
  1427. :return: output if there was any
  1428. """
  1429. self.report_usage('exec_command')
  1430. result = self.exec_command_test(text, False)
  1431. #MS: added this method call so the geometry is updated once the TCL
  1432. #command is executed
  1433. self.plot_all()
  1434. return result
  1435. def exec_command_test(self, text, reraise=True):
  1436. """
  1437. Same as exec_command(...) with additional control over exceptions.
  1438. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1439. :param text: Input command
  1440. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1441. :return: Output from the command
  1442. """
  1443. text = str(text)
  1444. try:
  1445. self.shell.open_proccessing() # Disables input box.
  1446. result = self.tcl.eval(str(text))
  1447. if result != 'None':
  1448. self.shell.append_output(result + '\n')
  1449. except tk.TclError as e:
  1450. # This will display more precise answer if something in TCL shell fails
  1451. result = self.tcl.eval("set errorInfo")
  1452. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1453. self.shell.append_error('ERROR: ' + result + '\n')
  1454. # Show error in console and just return or in test raise exception
  1455. if reraise:
  1456. raise e
  1457. finally:
  1458. self.shell.close_proccessing()
  1459. pass
  1460. return result
  1461. # """
  1462. # Code below is unsused. Saved for later.
  1463. # """
  1464. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1465. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1466. # self.log.debug(parts)
  1467. # try:
  1468. # if parts[0] not in commands:
  1469. # self.shell.append_error("Unknown command\n")
  1470. # return
  1471. #
  1472. # #import inspect
  1473. # #inspect.getargspec(someMethod)
  1474. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1475. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1476. # self.shell.append_error(
  1477. # "Command %s takes %d arguments. %d given.\n" %
  1478. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1479. # )
  1480. # return
  1481. #
  1482. # cmdfcn = commands[parts[0]]["fcn"]
  1483. # cmdconv = commands[parts[0]]["converters"]
  1484. # if len(parts) - 1 > 0:
  1485. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1486. # else:
  1487. # retval = cmdfcn()
  1488. # retfcn = commands[parts[0]]["retfcn"]
  1489. # if retval and retfcn(retval):
  1490. # self.shell.append_output(retfcn(retval) + "\n")
  1491. #
  1492. # except Exception as e:
  1493. # #self.shell.append_error(''.join(traceback.format_exc()))
  1494. # #self.shell.append_error("?\n")
  1495. # self.shell.append_error(str(e) + "\n")
  1496. def info(self, msg):
  1497. """
  1498. Informs the user. Normally on the status bar, optionally
  1499. also on the shell.
  1500. :param msg: Text to write.
  1501. :return: None
  1502. """
  1503. # Type of message in brackets at the begining of the message.
  1504. match = re.search("\[([^\]]+)\](.*)", msg)
  1505. if match:
  1506. level = match.group(1)
  1507. msg_ = match.group(2)
  1508. self.ui.fcinfo.set_status(str(msg_), level=level)
  1509. if level == "error" or level == "warning":
  1510. self.shell_message(msg, error=True, show=True)
  1511. elif level == "error_notcl" or level == "warning_notcl":
  1512. self.shell_message(msg, error=True, show=False)
  1513. else:
  1514. self.shell_message(msg, error=False, show=False)
  1515. else:
  1516. self.ui.fcinfo.set_status(str(msg), level="info")
  1517. # make sure that if the message is to clear the infobar with a space
  1518. # is not printed over and over on the shell
  1519. if msg != '':
  1520. self.shell_message(msg)
  1521. def restore_toolbar_view(self):
  1522. tb = self.defaults["global_toolbar_view"]
  1523. if tb & 1:
  1524. self.ui.toolbarfile.setVisible(True)
  1525. else:
  1526. self.ui.toolbarfile.setVisible(False)
  1527. if tb & 2:
  1528. self.ui.toolbargeo.setVisible(True)
  1529. else:
  1530. self.ui.toolbargeo.setVisible(False)
  1531. if tb & 4:
  1532. self.ui.toolbarview.setVisible(True)
  1533. else:
  1534. self.ui.toolbarview.setVisible(False)
  1535. if tb & 8:
  1536. self.ui.toolbartools.setVisible(True)
  1537. else:
  1538. self.ui.toolbartools.setVisible(False)
  1539. if tb & 16:
  1540. self.ui.snap_toolbar.setVisible(True)
  1541. else:
  1542. self.ui.snap_toolbar.setVisible(False)
  1543. def load_defaults(self, filename):
  1544. """
  1545. Loads the aplication's default settings from current_defaults.FlatConfig into
  1546. ``self.defaults``.
  1547. :return: None
  1548. """
  1549. try:
  1550. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1551. options = f.read()
  1552. f.close()
  1553. except IOError:
  1554. self.log.error("Could not load defaults file.")
  1555. self.inform.emit("[error] Could not load defaults file.")
  1556. # in case the defaults file can't be loaded, show all toolbars
  1557. self.defaults["global_toolbar_view"] = 31
  1558. return
  1559. try:
  1560. defaults = json.loads(options)
  1561. except:
  1562. # in case the defaults file can't be loaded, show all toolbars
  1563. self.defaults["global_toolbar_view"] = 31
  1564. e = sys.exc_info()[0]
  1565. App.log.error(str(e))
  1566. self.inform.emit("[error] Failed to parse defaults file.")
  1567. return
  1568. self.defaults.update(defaults)
  1569. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1570. # restore the toolbar view
  1571. self.restore_toolbar_view()
  1572. def on_import_preferences(self):
  1573. """
  1574. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1575. ``self.defaults``.
  1576. :return: None
  1577. """
  1578. self.report_usage("on_import_preferences")
  1579. App.log.debug("on_import_preferences()")
  1580. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1581. try:
  1582. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences",
  1583. directory=self.data_path, filter=filter)
  1584. except TypeError:
  1585. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences", filter=filter)
  1586. filename = str(filename)
  1587. if filename == "":
  1588. self.inform.emit("[warning_notcl]FlatCAM preferences import cancelled.")
  1589. else:
  1590. try:
  1591. f = open(filename)
  1592. options = f.read()
  1593. f.close()
  1594. except IOError:
  1595. self.log.error("Could not load defaults file.")
  1596. self.inform.emit("[error_notcl] Could not load defaults file.")
  1597. return
  1598. try:
  1599. defaults_from_file = json.loads(options)
  1600. except:
  1601. e = sys.exc_info()[0]
  1602. App.log.error(str(e))
  1603. self.inform.emit("[error_notcl] Failed to parse defaults file.")
  1604. return
  1605. self.defaults.update(defaults_from_file)
  1606. self.inform.emit("[success]Imported Defaults from %s" %filename)
  1607. def on_export_preferences(self):
  1608. self.report_usage("on_export_preferences")
  1609. App.log.debug("on_export_preferences()")
  1610. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1611. try:
  1612. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences",
  1613. directory=self.data_path, filter=filter)
  1614. except TypeError:
  1615. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences", filter=filter)
  1616. filename = str(filename)
  1617. defaults_from_file = {}
  1618. if filename == "":
  1619. self.inform.emit("[warning_notcl]FlatCAM preferences export cancelled.")
  1620. return
  1621. else:
  1622. try:
  1623. f = open(filename, 'w')
  1624. defaults_file_content = f.read()
  1625. f.close()
  1626. except IOError:
  1627. App.log.debug('Creating a new preferences file ...')
  1628. f = open(filename, 'w')
  1629. json.dump({}, f)
  1630. f.close()
  1631. except:
  1632. e = sys.exc_info()[0]
  1633. App.log.error("Could not load defaults file.")
  1634. App.log.error(str(e))
  1635. self.inform.emit("[error_notcl]Could not load defaults file.")
  1636. return
  1637. try:
  1638. defaults_from_file = json.loads(defaults_file_content)
  1639. except:
  1640. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1641. # Update options
  1642. self.defaults_read_form()
  1643. defaults_from_file.update(self.defaults)
  1644. self.propagate_defaults(silent=True)
  1645. # Save update options
  1646. try:
  1647. f = open(filename, "w")
  1648. json.dump(defaults_from_file, f)
  1649. f.close()
  1650. except:
  1651. self.inform.emit("[error_notcl] Failed to write defaults to file.")
  1652. return
  1653. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1654. def on_preferences_open_folder(self):
  1655. if sys.platform == 'win32':
  1656. subprocess.Popen('explorer %s' % self.data_path)
  1657. elif sys.platform == 'darwin':
  1658. os.system('open "%s"' % self.data_path)
  1659. else:
  1660. subprocess.Popen(['xdg-open', self.data_path])
  1661. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1662. def save_geometry(self, x, y, width, height, notebook_width):
  1663. self.defaults["global_def_win_x"] = x
  1664. self.defaults["global_def_win_y"] = y
  1665. self.defaults["global_def_win_w"] = width
  1666. self.defaults["global_def_win_h"] = height
  1667. self.defaults["def_notebook_width"] = notebook_width
  1668. self.save_defaults()
  1669. def message_dialog(self, title, message, kind="info"):
  1670. icon = {"info": QtWidgets.QMessageBox.Information,
  1671. "warning": QtWidgets.QMessageBox.Warning,
  1672. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1673. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1674. dlg.setText(message)
  1675. dlg.exec_()
  1676. def register_recent(self, kind, filename):
  1677. self.log.debug("register_recent()")
  1678. self.log.debug(" %s" % kind)
  1679. self.log.debug(" %s" % filename)
  1680. record = {'kind': str(kind), 'filename': str(filename)}
  1681. if record in self.recent:
  1682. return
  1683. self.recent.insert(0, record)
  1684. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1685. self.recent.pop()
  1686. try:
  1687. f = open(self.data_path + '/recent.json', 'w')
  1688. except IOError:
  1689. App.log.error("Failed to open recent items file for writing.")
  1690. self.inform.emit('[error_notcl]Failed to open recent files file for writing.')
  1691. return
  1692. #try:
  1693. json.dump(self.recent, f)
  1694. # except:
  1695. # App.log.error("Failed to write to recent items file.")
  1696. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1697. # f.close()
  1698. f.close()
  1699. # Re-buid the recent items menu
  1700. self.setup_recent_items()
  1701. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1702. """
  1703. Creates a new specalized FlatCAMObj and attaches it to the application,
  1704. this is, updates the GUI accordingly, any other records and plots it.
  1705. This method is thread-safe.
  1706. Notes:
  1707. * If the name is in use, the self.collection will modify it
  1708. when appending it to the collection. There is no need to handle
  1709. name conflicts here.
  1710. :param kind: The kind of object to create. One of 'gerber',
  1711. 'excellon', 'cncjob' and 'geometry'.
  1712. :type kind: str
  1713. :param name: Name for the object.
  1714. :type name: str
  1715. :param initialize: Function to run after creation of the object
  1716. but before it is attached to the application. The function is
  1717. called with 2 parameters: the new object and the App instance.
  1718. :type initialize: function
  1719. :return: None
  1720. :rtype: None
  1721. """
  1722. App.log.debug("new_object()")
  1723. self.plot = plot
  1724. self.autoselected = autoselected
  1725. t0 = time.time() # Debug
  1726. ## Create object
  1727. classdict = {
  1728. "gerber": FlatCAMGerber,
  1729. "excellon": FlatCAMExcellon,
  1730. "cncjob": FlatCAMCNCjob,
  1731. "geometry": FlatCAMGeometry
  1732. }
  1733. App.log.debug("Calling object constructor...")
  1734. obj = classdict[kind](name)
  1735. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1736. # Set options from "Project options" form
  1737. self.options_read_form()
  1738. # IMPORTANT
  1739. # The key names in defaults and options dictionary's are not random:
  1740. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1741. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1742. # the options from project options form into the self.options. After that, below, depending on the type of
  1743. # object that is created, it will strip the name of the object and the underline (if the original key was
  1744. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1745. # "toolchange"
  1746. for option in self.options:
  1747. if option.find(kind + "_") == 0:
  1748. oname = option[len(kind) + 1:]
  1749. obj.options[oname] = self.options[option]
  1750. # if kind == 'geometry':
  1751. # obj.tools = {}
  1752. # elif kind == 'cncjob':
  1753. # obj.cnc_tools = {}
  1754. # Initialize as per user request
  1755. # User must take care to implement initialize
  1756. # in a thread-safe way as is is likely that we
  1757. # have been invoked in a separate thread.
  1758. t1 = time.time()
  1759. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1760. try:
  1761. return_value = initialize(obj, self)
  1762. except Exception as e:
  1763. msg = "[error_notcl] An internal error has ocurred. See shell.\n"
  1764. msg += "Object (%s) failed because: %s \n\n" % (kind, str(e))
  1765. msg += traceback.format_exc()
  1766. self.inform.emit(msg)
  1767. # if str(e) == "Empty Geometry":
  1768. # self.inform.emit("[error_notcl] )
  1769. # else:
  1770. # self.inform.emit("[error] Object (%s) failed because: %s" % (kind, str(e)))
  1771. return "fail"
  1772. t2 = time.time()
  1773. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1774. if return_value == 'fail':
  1775. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  1776. return "fail"
  1777. # Check units and convert if necessary
  1778. # This condition CAN be true because initialize() can change obj.units
  1779. if self.options["units"].upper() != obj.units.upper():
  1780. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1781. obj.convert_units(self.options["units"])
  1782. t3 = time.time()
  1783. self.log.debug("%f seconds converting units." % (t3 - t2))
  1784. # Create the bounding box for the object and then add the results to the obj.options
  1785. try:
  1786. xmin, ymin, xmax, ymax = obj.bounds()
  1787. obj.options['xmin'] = xmin
  1788. obj.options['ymin'] = ymin
  1789. obj.options['xmax'] = xmax
  1790. obj.options['ymax'] = ymax
  1791. except:
  1792. log.warning("The object has no bounds properties.")
  1793. pass
  1794. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1795. # Move the object to the main thread and let the app know that it is available.
  1796. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  1797. self.object_created.emit(obj, self.plot, self.autoselected)
  1798. return obj
  1799. def new_excellon_object(self):
  1800. self.new_object('excellon', 'new_e', lambda x, y: None)
  1801. def on_object_created(self, obj, plot, autoselect):
  1802. """
  1803. Event callback for object creation.
  1804. :param obj: The newly created FlatCAM object.
  1805. :return: None
  1806. """
  1807. t0 = time.time() # DEBUG
  1808. self.log.debug("on_object_created()")
  1809. # The Collection might change the name if there is a collision
  1810. self.collection.append(obj)
  1811. # after adding the object to the collection always update the list of objects that are in the collection
  1812. self.all_objects_list = self.collection.get_list()
  1813. self.inform.emit("[success]Object (%s) created: %s" % (obj.kind, obj.options['name']))
  1814. self.new_object_available.emit(obj)
  1815. # update the SHELL auto-completer model with the name of the new object
  1816. self.myKeywords.append(obj.options['name'])
  1817. self.shell._edit.set_model_data(self.myKeywords)
  1818. if autoselect:
  1819. # select the just opened object but deselect the previous ones
  1820. self.collection.set_all_inactive()
  1821. self.collection.set_active(obj.options["name"])
  1822. def worker_task(obj):
  1823. with self.proc_container.new("Plotting"):
  1824. obj.plot()
  1825. t1 = time.time() # DEBUG
  1826. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1827. self.object_plotted.emit(obj)
  1828. # Send to worker
  1829. # self.worker.add_task(worker_task, [self])
  1830. if plot:
  1831. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  1832. def on_object_changed(self, obj):
  1833. # update the bounding box data from obj.options
  1834. xmin, ymin, xmax, ymax = obj.bounds()
  1835. obj.options['xmin'] = xmin
  1836. obj.options['ymin'] = ymin
  1837. obj.options['xmax'] = xmax
  1838. obj.options['ymax'] = ymax
  1839. log.debug("Object changed, updating the bounding box data on self.options")
  1840. # delete the old selection shape
  1841. self.delete_selection_shape()
  1842. def on_object_plotted(self, obj):
  1843. self.on_zoom_fit(None)
  1844. def options_read_form(self):
  1845. for option in self.options_form_fields:
  1846. self.options[option] = self.options_form_fields[option].get_value()
  1847. def options_write_form(self):
  1848. for option in self.options:
  1849. self.options_write_form_field(option)
  1850. def options_write_form_field(self, field):
  1851. try:
  1852. self.options_form_fields[field].set_value(self.options[field])
  1853. except KeyError:
  1854. # Changed from error to debug. This allows to have data stored
  1855. # which is not user-editable.
  1856. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  1857. pass
  1858. def on_about(self):
  1859. """
  1860. Displays the "about" dialog.
  1861. :return: None
  1862. """
  1863. self.report_usage("on_about")
  1864. version = self.version
  1865. version_date = self.version_date
  1866. beta = self.beta
  1867. class AboutDialog(QtWidgets.QDialog):
  1868. def __init__(self, parent=None):
  1869. QtWidgets.QDialog.__init__(self, parent)
  1870. # Icon and title
  1871. self.setWindowIcon(parent.app_icon)
  1872. self.setWindowTitle("FlatCAM")
  1873. layout1 = QtWidgets.QVBoxLayout()
  1874. self.setLayout(layout1)
  1875. layout2 = QtWidgets.QHBoxLayout()
  1876. layout1.addLayout(layout2)
  1877. logo = QtWidgets.QLabel()
  1878. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  1879. layout2.addWidget(logo, stretch=0)
  1880. title = QtWidgets.QLabel(
  1881. "<font size=8><B>FlatCAM</B></font><BR>"
  1882. "Version %s %s (%s) - %s <BR>"
  1883. "<BR>"
  1884. "2D Computer-Aided Printed Circuit Board<BR>"
  1885. "Manufacturing.<BR>"
  1886. "<BR>"
  1887. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  1888. "<BR>"
  1889. "<B> Main Contributors:</B><BR>"
  1890. "Denis Hayrullin<BR>"
  1891. "Kamil Sopko<BR>"
  1892. "Marius Stanciu<BR>"
  1893. "Matthieu Berthomé<BR>"
  1894. "and many others found "
  1895. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  1896. "<BR>"
  1897. "Development is done "
  1898. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  1899. "DOWNLOAD area "
  1900. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  1901. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  1902. )
  1903. title.setOpenExternalLinks(True)
  1904. layout2.addWidget(title, stretch=1)
  1905. layout3 = QtWidgets.QHBoxLayout()
  1906. layout1.addLayout(layout3)
  1907. layout3.addStretch()
  1908. okbtn = QtWidgets.QPushButton("Close")
  1909. layout3.addWidget(okbtn)
  1910. okbtn.clicked.connect(self.accept)
  1911. AboutDialog(self.ui).exec_()
  1912. def on_file_savedefaults(self):
  1913. """
  1914. Callback for menu item File->Save Defaults. Saves application default options
  1915. ``self.defaults`` to current_defaults.FlatConfig.
  1916. :return: None
  1917. """
  1918. self.save_defaults()
  1919. def on_app_exit(self):
  1920. if self.collection.get_list():
  1921. msgbox = QtWidgets.QMessageBox()
  1922. # msgbox.setText("<B>Save changes ...</B>")
  1923. msgbox.setText("There are files/objects opened in FlatCAM. "
  1924. "\n"
  1925. "Do you want to Save the project?")
  1926. msgbox.setWindowTitle("Save changes")
  1927. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  1928. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  1929. QtWidgets.QMessageBox.Cancel)
  1930. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  1931. response = msgbox.exec_()
  1932. if response == QtWidgets.QMessageBox.Yes:
  1933. self.on_file_saveprojectas(thread=False)
  1934. elif response == QtWidgets.QMessageBox.Cancel:
  1935. return
  1936. self.save_defaults()
  1937. else:
  1938. self.save_defaults()
  1939. log.debug("Application defaults saved ... Exit event.")
  1940. QtWidgets.qApp.quit()
  1941. def save_defaults(self, silent=False):
  1942. """
  1943. Saves application default options
  1944. ``self.defaults`` to current_defaults.FlatConfig.
  1945. :return: None
  1946. """
  1947. self.report_usage("save_defaults")
  1948. # Read options from file
  1949. try:
  1950. f = open(self.data_path + "/current_defaults.FlatConfig")
  1951. defaults_file_content = f.read()
  1952. f.close()
  1953. except:
  1954. e = sys.exc_info()[0]
  1955. App.log.error("Could not load defaults file.")
  1956. App.log.error(str(e))
  1957. self.inform.emit("[error_notcl] Could not load defaults file.")
  1958. return
  1959. try:
  1960. defaults = json.loads(defaults_file_content)
  1961. except:
  1962. e = sys.exc_info()[0]
  1963. App.log.error("Failed to parse defaults file.")
  1964. App.log.error(str(e))
  1965. self.inform.emit("[error_notcl] Failed to parse defaults file.")
  1966. return
  1967. # Update options
  1968. self.defaults_read_form()
  1969. defaults.update(self.defaults)
  1970. self.propagate_defaults(silent=True)
  1971. # Save update options
  1972. try:
  1973. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  1974. json.dump(defaults, f)
  1975. f.close()
  1976. except:
  1977. self.inform.emit("[error_notcl] Failed to write defaults to file.")
  1978. return
  1979. # Save the toolbar view
  1980. tb_status = 0
  1981. if self.ui.toolbarfile.isVisible():
  1982. tb_status += 1
  1983. if self.ui.toolbargeo.isVisible():
  1984. tb_status += 2
  1985. if self.ui.toolbarview.isVisible():
  1986. tb_status += 4
  1987. if self.ui.toolbartools.isVisible():
  1988. tb_status += 8
  1989. if self.ui.snap_toolbar.isVisible():
  1990. tb_status += 16
  1991. self.defaults["global_toolbar_view"] = tb_status
  1992. if not silent:
  1993. self.inform.emit("[success]Defaults saved.")
  1994. def save_factory_defaults(self, silent=False):
  1995. """
  1996. Saves application factory default options
  1997. ``self.defaults`` to factory_defaults.FlatConfig.
  1998. It's a one time job done just after the first install.
  1999. :return: None
  2000. """
  2001. self.report_usage("save_factory_defaults")
  2002. # Read options from file
  2003. try:
  2004. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2005. factory_defaults_file_content = f_f_def.read()
  2006. f_f_def.close()
  2007. except:
  2008. e = sys.exc_info()[0]
  2009. App.log.error("Could not load factory defaults file.")
  2010. App.log.error(str(e))
  2011. self.inform.emit("[error_notcl] Could not load factory defaults file.")
  2012. return
  2013. try:
  2014. factory_defaults = json.loads(factory_defaults_file_content)
  2015. except:
  2016. e = sys.exc_info()[0]
  2017. App.log.error("Failed to parse factory defaults file.")
  2018. App.log.error(str(e))
  2019. self.inform.emit("[error_notcl] Failed to parse factory defaults file.")
  2020. return
  2021. # Update options
  2022. self.defaults_read_form()
  2023. factory_defaults.update(self.defaults)
  2024. self.propagate_defaults(silent=True)
  2025. # Save update options
  2026. try:
  2027. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2028. json.dump(factory_defaults, f_f_def_s)
  2029. f_f_def_s.close()
  2030. except:
  2031. self.inform.emit("[error_notcl] Failed to write factory defaults to file.")
  2032. return
  2033. if silent is False:
  2034. self.inform.emit("Factory defaults saved.")
  2035. def final_save(self):
  2036. if self.collection.get_list():
  2037. msgbox = QtWidgets.QMessageBox()
  2038. # msgbox.setText("<B>Save changes ...</B>")
  2039. msgbox.setText("There are files/objects opened in FlatCAM. "
  2040. "\n"
  2041. "Do you want to Save the project?")
  2042. msgbox.setWindowTitle("Save changes")
  2043. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2044. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2045. QtWidgets.QMessageBox.Cancel)
  2046. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2047. response = msgbox.exec_()
  2048. if response == QtWidgets.QMessageBox.Yes:
  2049. self.on_file_saveprojectas(thread=False)
  2050. elif response == QtWidgets.QMessageBox.Cancel:
  2051. self.should_we_quit = False
  2052. return
  2053. self.save_defaults()
  2054. log.debug("Application defaults saved ... Exit event.")
  2055. def on_toggle_shell(self):
  2056. """
  2057. toggle shell if is visible close it if closed open it
  2058. :return:
  2059. """
  2060. if self.ui.shell_dock.isVisible():
  2061. self.ui.shell_dock.hide()
  2062. else:
  2063. self.ui.shell_dock.show()
  2064. def on_edit_join(self, name=None):
  2065. """
  2066. Callback for Edit->Join. Joins the selected geometry objects into
  2067. a new one.
  2068. :return: None
  2069. """
  2070. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2071. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2072. tooldias = []
  2073. geo_type_list = []
  2074. objs = self.collection.get_selected()
  2075. for obj in objs:
  2076. geo_type_list.append(obj.multigeo)
  2077. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2078. if len(set(geo_type_list)) != 1:
  2079. self.inform.emit("[error] Failed join. The Geometry objects are of different types.\n"
  2080. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2081. "convert from one to another and retry joining \n"
  2082. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2083. "the result may not be what was expected. \n"
  2084. "Check the generated GCODE.")
  2085. return
  2086. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2087. if True in geo_type_list:
  2088. def initialize(obj, app):
  2089. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2090. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2091. for v in obj.tools.values():
  2092. v['data']['name'] = obj_name_multi
  2093. self.new_object("geometry", obj_name_multi, initialize)
  2094. else:
  2095. def initialize(obj, app):
  2096. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2097. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2098. for v in obj.tools.values():
  2099. v['data']['name'] = obj_name_single
  2100. self.new_object("geometry", obj_name_single, initialize)
  2101. def on_edit_join_exc(self):
  2102. """
  2103. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2104. a new one.
  2105. :return: None
  2106. """
  2107. objs = self.collection.get_selected()
  2108. for obj in objs:
  2109. if not isinstance(obj, FlatCAMExcellon):
  2110. self.inform.emit("[error_notcl]Failed. Excellon joining works only on Excellon objects.")
  2111. return
  2112. def initialize(obj, app):
  2113. FlatCAMExcellon.merge(objs, obj)
  2114. self.new_object("excellon", 'Combo_Excellon', initialize)
  2115. def on_edit_join_grb(self):
  2116. """
  2117. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2118. a new one.
  2119. :return: None
  2120. """
  2121. objs = self.collection.get_selected()
  2122. for obj in objs:
  2123. if not isinstance(obj, FlatCAMGerber):
  2124. self.inform.emit("[error_notcl]Failed. Gerber joining works only on Gerber objects.")
  2125. return
  2126. def initialize(obj, app):
  2127. FlatCAMGerber.merge(objs, obj)
  2128. self.new_object("gerber", 'Combo_Gerber', initialize)
  2129. def on_convert_singlegeo_to_multigeo(self):
  2130. obj = self.collection.get_active()
  2131. if obj is None:
  2132. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  2133. return
  2134. if not isinstance(obj, FlatCAMGeometry):
  2135. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  2136. return
  2137. obj.multigeo = True
  2138. for tooluid, dict_value in obj.tools.items():
  2139. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2140. if not isinstance(obj.solid_geometry, list):
  2141. obj.solid_geometry = [obj.solid_geometry]
  2142. obj.solid_geometry[:] = []
  2143. obj.plot()
  2144. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  2145. def on_convert_multigeo_to_singlegeo(self):
  2146. obj = self.collection.get_active()
  2147. if obj is None:
  2148. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  2149. return
  2150. if not isinstance(obj, FlatCAMGeometry):
  2151. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  2152. return
  2153. obj.multigeo = False
  2154. total_solid_geometry = []
  2155. for tooluid, dict_value in obj.tools.items():
  2156. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2157. # clear the original geometry
  2158. dict_value['solid_geometry'][:] = []
  2159. obj.solid_geometry = deepcopy(total_solid_geometry)
  2160. obj.plot()
  2161. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  2162. def on_options_dict_change(self, field):
  2163. self.options_write_form_field(field)
  2164. if field == "units":
  2165. self.set_screen_units(self.options['units'])
  2166. def on_defaults_dict_change(self, field):
  2167. self.defaults_write_form_field(field)
  2168. def set_screen_units(self, units):
  2169. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  2170. def on_toggle_units(self):
  2171. """
  2172. Callback for the Units radio-button change in the Options tab.
  2173. Changes the application's default units or the current project's units.
  2174. If changing the project's units, the change propagates to all of
  2175. the objects in the project.
  2176. :return: None
  2177. """
  2178. self.report_usage("on_toggle_units")
  2179. if self.toggle_units_ignore:
  2180. return
  2181. # If option is the same, then ignore
  2182. if self.general_options_form.general_app_group.units_radio.get_value().upper() == self.options["units"].upper():
  2183. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  2184. return
  2185. # Options to scale
  2186. dimensions = ['gerber_isotooldia', 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2187. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','tools_nccoverlap',
  2188. 'tools_nccmargin','tools_cutouttooldia','tools_cutoutgapsize',
  2189. 'gerber_noncoppermargin','gerber_bboxmargin',
  2190. 'excellon_drillz', "excellon_toolchangexy",
  2191. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2192. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  2193. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  2194. 'geometry_cnctooldia', 'tools_painttooldia', 'tools_paintoverlap', 'geometry_toolchangexy',
  2195. 'geometry_toolchangez',
  2196. 'tools_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  2197. def scale_options(sfactor):
  2198. for dim in dimensions:
  2199. if dim == 'excellon_toolchangexy':
  2200. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2201. coords_xy[0] *= sfactor
  2202. coords_xy[1] *= sfactor
  2203. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2204. elif dim == 'geometry_toolchangexy':
  2205. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2206. coords_xy[0] *= sfactor
  2207. coords_xy[1] *= sfactor
  2208. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2209. else:
  2210. self.options[dim] *= sfactor
  2211. # The scaling factor depending on choice of units.
  2212. factor = 1/25.4
  2213. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2214. factor = 25.4
  2215. # Changing project units. Warn user.
  2216. msgbox = QtWidgets.QMessageBox()
  2217. msgbox.setText("<B>Change project units ...</B>")
  2218. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2219. "properties of all objects to be scaled accordingly. Continue?")
  2220. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2221. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2222. response = msgbox.exec_()
  2223. if response == QtWidgets.QMessageBox.Ok:
  2224. self.options_read_form()
  2225. scale_options(factor)
  2226. self.options_write_form()
  2227. # change this only if the workspace is active
  2228. if self.defaults['global_workspace'] is True:
  2229. self.plotcanvas.draw_workspace()
  2230. # adjust the grid values on the main toolbar
  2231. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2232. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2233. for obj in self.collection.get_list():
  2234. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2235. obj.convert_units(units)
  2236. # make that the properties stored in the object are also updated
  2237. self.object_changed.emit(obj)
  2238. obj.build_ui()
  2239. current = self.collection.get_active()
  2240. if current is not None:
  2241. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2242. if not isinstance(current, FlatCAMGeometry):
  2243. current.to_form()
  2244. self.plot_all()
  2245. else:
  2246. # Undo toggling
  2247. self.toggle_units_ignore = True
  2248. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2249. self.general_options_form.general_app_group.units_radio.set_value('IN')
  2250. else:
  2251. self.general_options_form.general_app_group.units_radio.set_value('MM')
  2252. self.toggle_units_ignore = False
  2253. self.options_read_form()
  2254. self.inform.emit("Converted units to %s" % self.options["units"])
  2255. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  2256. self.set_screen_units(self.options["units"])
  2257. def on_toggle_units_click(self):
  2258. if self.options["units"] == 'MM':
  2259. self.general_options_form.general_app_group.units_radio.set_value("IN")
  2260. else:
  2261. self.general_options_form.general_app_group.units_radio.set_value("MM")
  2262. self.on_toggle_units()
  2263. def on_language_apply(self):
  2264. # TODO: apply the language
  2265. # app restart section
  2266. pass
  2267. def on_fullscreen(self):
  2268. if self.toggle_fscreen is False:
  2269. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2270. tb.setVisible(False)
  2271. self.ui.notebook.setVisible(False)
  2272. self.toggle_fscreen = True
  2273. else:
  2274. self.restore_toolbar_view()
  2275. self.ui.notebook.setVisible(True)
  2276. self.toggle_fscreen = False
  2277. def on_toggle_axis(self):
  2278. if self.toggle_axis is False:
  2279. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2280. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2281. self.plotcanvas.redraw()
  2282. self.toggle_axis = True
  2283. else:
  2284. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2285. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2286. self.plotcanvas.redraw()
  2287. self.toggle_axis = False
  2288. def on_toggle_grid(self):
  2289. self.ui.grid_snap_btn.trigger()
  2290. def on_options_combo_change(self, sel):
  2291. """
  2292. Called when the combo box to choose between application defaults and
  2293. project option changes value. The corresponding variables are
  2294. copied to the UI.
  2295. :param sel: The option index that was chosen.
  2296. :return: None
  2297. """
  2298. # combo_sel = self.ui.notebook.combo_options.get_active()
  2299. App.log.debug("Options --> %s" % sel)
  2300. # form = [self.defaults_form, self.options_form][sel]
  2301. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2302. if sel == 0:
  2303. self.gen_form = self.general_defaults_form
  2304. self.ger_form = self.gerber_defaults_form
  2305. self.exc_form = self.excellon_defaults_form
  2306. self.geo_form = self.geometry_defaults_form
  2307. self.cnc_form = self.cncjob_defaults_form
  2308. self.tools_form = self.tools_defaults_form
  2309. elif sel == 1:
  2310. self.gen_form = self.general_options_form
  2311. self.ger_form = self.gerber_options_form
  2312. self.exc_form = self.excellon_options_form
  2313. self.geo_form = self.geometry_options_form
  2314. self.cnc_form = self.cncjob_options_form
  2315. self.tools_form = self.tools_options_form
  2316. else:
  2317. return
  2318. try:
  2319. self.ui.general_scroll_area.takeWidget()
  2320. except:
  2321. self.log.debug("Nothing to remove")
  2322. self.ui.general_scroll_area.setWidget(self.gen_form)
  2323. self.gen_form.show()
  2324. try:
  2325. self.ui.gerber_scroll_area.takeWidget()
  2326. except:
  2327. self.log.debug("Nothing to remove")
  2328. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2329. self.ger_form.show()
  2330. try:
  2331. self.ui.excellon_scroll_area.takeWidget()
  2332. except:
  2333. self.log.debug("Nothing to remove")
  2334. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2335. self.exc_form.show()
  2336. try:
  2337. self.ui.geometry_scroll_area.takeWidget()
  2338. except:
  2339. self.log.debug("Nothing to remove")
  2340. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2341. self.geo_form.show()
  2342. try:
  2343. self.ui.cncjob_scroll_area.takeWidget()
  2344. except:
  2345. self.log.debug("Nothing to remove")
  2346. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2347. self.cnc_form.show()
  2348. try:
  2349. self.ui.tools_scroll_area.takeWidget()
  2350. except:
  2351. self.log.debug("Nothing to remove")
  2352. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2353. self.tools_form.show()
  2354. self.log.debug("Finished GUI form initialization.")
  2355. # self.options2form()
  2356. def on_excellon_defaults_button(self):
  2357. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2358. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2359. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2360. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2361. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2362. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2363. log.debug("Excellon app defaults loaded ...")
  2364. def on_excellon_options_button(self):
  2365. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2366. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2367. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2368. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2369. self.options_form_fields["excellon_zeros"].set_value('L')
  2370. self.options_form_fields["excellon_units"].set_value('INCH')
  2371. log.debug("Excellon options defaults loaded ...")
  2372. # Setting plot colors handlers
  2373. def on_pf_color_entry(self):
  2374. self.defaults['global_plot_fill'] = self.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2375. self.defaults['global_plot_fill'][7:9]
  2376. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2377. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2378. def on_pf_color_button(self):
  2379. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2380. c_dialog = QtWidgets.QColorDialog()
  2381. plot_fill_color = c_dialog.getColor(initial=current_color)
  2382. if plot_fill_color.isValid() is False:
  2383. return
  2384. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2385. "background-color:%s" % str(plot_fill_color.name()))
  2386. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2387. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2388. self.defaults['global_plot_fill'] = new_val
  2389. def on_pf_color_spinner(self):
  2390. spinner_value = self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2391. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2392. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2393. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2394. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2395. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2396. def on_pf_color_slider(self):
  2397. slider_value = self.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2398. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2399. def on_pl_color_entry(self):
  2400. self.defaults['global_plot_line'] = self.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2401. self.defaults['global_plot_line'][7:9]
  2402. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2403. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2404. def on_pl_color_button(self):
  2405. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2406. # print(current_color)
  2407. c_dialog = QtWidgets.QColorDialog()
  2408. plot_line_color = c_dialog.getColor(initial=current_color)
  2409. if plot_line_color.isValid() is False:
  2410. return
  2411. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2412. "background-color:%s" % str(plot_line_color.name()))
  2413. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2414. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2415. self.defaults['global_plot_line'] = new_val_line
  2416. # Setting selection colors (left - right) handlers
  2417. def on_sf_color_entry(self):
  2418. self.defaults['global_sel_fill'] = self.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2419. self.defaults['global_sel_fill'][7:9]
  2420. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2421. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2422. def on_sf_color_button(self):
  2423. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2424. c_dialog = QtWidgets.QColorDialog()
  2425. plot_fill_color = c_dialog.getColor(initial=current_color)
  2426. if plot_fill_color.isValid() is False:
  2427. return
  2428. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2429. "background-color:%s" % str(plot_fill_color.name()))
  2430. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2431. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2432. self.defaults['global_sel_fill'] = new_val
  2433. def on_sf_color_spinner(self):
  2434. spinner_value = self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2435. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2436. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2437. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2438. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2439. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2440. def on_sf_color_slider(self):
  2441. slider_value = self.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2442. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2443. def on_sl_color_entry(self):
  2444. self.defaults['global_sel_line'] = self.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2445. self.defaults['global_sel_line'][7:9]
  2446. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2447. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2448. def on_sl_color_button(self):
  2449. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2450. c_dialog = QtWidgets.QColorDialog()
  2451. plot_line_color = c_dialog.getColor(initial=current_color)
  2452. if plot_line_color.isValid() is False:
  2453. return
  2454. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2455. "background-color:%s" % str(plot_line_color.name()))
  2456. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2457. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2458. self.defaults['global_sel_line'] = new_val_line
  2459. # Setting selection colors (right - left) handlers
  2460. def on_alt_sf_color_entry(self):
  2461. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_gui_group \
  2462. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2463. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2464. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2465. def on_alt_sf_color_button(self):
  2466. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2467. c_dialog = QtWidgets.QColorDialog()
  2468. plot_fill_color = c_dialog.getColor(initial=current_color)
  2469. if plot_fill_color.isValid() is False:
  2470. return
  2471. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2472. "background-color:%s" % str(plot_fill_color.name()))
  2473. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2474. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2475. self.defaults['global_alt_sel_fill'] = new_val
  2476. def on_alt_sf_color_spinner(self):
  2477. spinner_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2478. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2479. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2480. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2481. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2482. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2483. def on_alt_sf_color_slider(self):
  2484. slider_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2485. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2486. def on_alt_sl_color_entry(self):
  2487. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_gui_group \
  2488. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2489. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2490. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2491. def on_alt_sl_color_button(self):
  2492. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2493. c_dialog = QtWidgets.QColorDialog()
  2494. plot_line_color = c_dialog.getColor(initial=current_color)
  2495. if plot_line_color.isValid() is False:
  2496. return
  2497. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2498. "background-color:%s" % str(plot_line_color.name()))
  2499. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2500. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2501. self.defaults['global_alt_sel_line'] = new_val_line
  2502. # Setting Editor colors
  2503. def on_draw_color_entry(self):
  2504. self.defaults['global_draw_color'] = self.general_defaults_form.general_gui_group \
  2505. .draw_color_entry.get_value()
  2506. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2507. "background-color:%s" % str(self.defaults['global_draw_color']))
  2508. def on_draw_color_button(self):
  2509. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2510. c_dialog = QtWidgets.QColorDialog()
  2511. draw_color = c_dialog.getColor(initial=current_color)
  2512. if draw_color.isValid() is False:
  2513. return
  2514. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2515. "background-color:%s" % str(draw_color.name()))
  2516. new_val = str(draw_color.name())
  2517. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2518. self.defaults['global_draw_color'] = new_val
  2519. def on_sel_draw_color_entry(self):
  2520. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_gui_group \
  2521. .sel_draw_color_entry.get_value()
  2522. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2523. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2524. def on_sel_draw_color_button(self):
  2525. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2526. c_dialog = QtWidgets.QColorDialog()
  2527. sel_draw_color = c_dialog.getColor(initial=current_color)
  2528. if sel_draw_color.isValid() is False:
  2529. return
  2530. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2531. "background-color:%s" % str(sel_draw_color.name()))
  2532. new_val_sel = str(sel_draw_color.name())
  2533. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  2534. self.defaults['global_sel_draw_color'] = new_val_sel
  2535. def on_workspace_modified(self):
  2536. self.save_defaults(silent=True)
  2537. self.plotcanvas.draw_workspace()
  2538. def on_workspace(self):
  2539. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2540. self.plotcanvas.restore_workspace()
  2541. else:
  2542. self.plotcanvas.delete_workspace()
  2543. self.save_defaults(silent=True)
  2544. def on_workspace_menu(self):
  2545. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2546. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  2547. else:
  2548. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  2549. self.on_workspace()
  2550. def on_theme(self):
  2551. self.defaults["global_theme"] = self.general_defaults_form.general_gui_group.theme_combo.get_value()
  2552. def on_save_button(self):
  2553. self.save_defaults(silent=False)
  2554. # load the defaults so they are updated into the app
  2555. self.load_defaults(filename='current_defaults')
  2556. # Re-fresh project options
  2557. self.on_options_app2project()
  2558. def handleOpen(self):
  2559. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2560. "All Files (*.*)"
  2561. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2562. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2563. if path:
  2564. file = QtCore.QFile(path)
  2565. if file.open(QtCore.QIODevice.ReadOnly):
  2566. stream = QtCore.QTextStream(file)
  2567. self.gcode_edited = stream.readAll()
  2568. self.ui.code_editor.setPlainText(self.gcode_edited)
  2569. file.close()
  2570. def handlePrint(self):
  2571. dialog = QtPrintSupport.QPrintDialog()
  2572. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2573. self.ui.code_editor.document().print_(dialog.printer())
  2574. def handlePreview(self):
  2575. dialog = QtPrintSupport.QPrintPreviewDialog()
  2576. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2577. dialog.exec_()
  2578. def handleTextChanged(self):
  2579. # enable = not self.ui.code_editor.document().isEmpty()
  2580. # self.ui.buttonPrint.setEnabled(enable)
  2581. # self.ui.buttonPreview.setEnabled(enable)
  2582. pass
  2583. def handleSaveGCode(self):
  2584. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2585. "All Files (*.*)"
  2586. try:
  2587. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2588. caption="Export G-Code ...", directory=self.defaults["global_last_folder"], filter=_filter_)[0])
  2589. except TypeError:
  2590. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2591. try:
  2592. my_gcode = self.ui.code_editor.toPlainText()
  2593. with open(filename, 'w') as f:
  2594. for line in my_gcode:
  2595. f.write(line)
  2596. except FileNotFoundError:
  2597. self.inform.emit("[WARNING] No such file or directory")
  2598. return
  2599. # Just for adding it to the recent files list.
  2600. self.file_opened.emit("cncjob", filename)
  2601. self.file_saved.emit("cncjob", filename)
  2602. self.inform.emit("Saved to: " + filename)
  2603. def handleFindGCode(self):
  2604. flags = QtGui.QTextDocument.FindCaseSensitively
  2605. text_to_be_found = self.ui.entryFind.get_value()
  2606. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2607. if r is False:
  2608. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2609. def handleReplaceGCode(self):
  2610. old = self.ui.entryFind.get_value()
  2611. new = self.ui.entryReplace.get_value()
  2612. if self.ui.sel_all_cb.isChecked():
  2613. while True:
  2614. cursor = self.ui.code_editor.textCursor()
  2615. cursor.beginEditBlock()
  2616. flags = QtGui.QTextDocument.FindCaseSensitively
  2617. # self.ui.editor is the QPlainTextEdit
  2618. r = self.ui.code_editor.find(str(old), flags)
  2619. if r:
  2620. qc = self.ui.code_editor.textCursor()
  2621. if qc.hasSelection():
  2622. qc.insertText(new)
  2623. else:
  2624. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2625. break
  2626. # Mark end of undo block
  2627. cursor.endEditBlock()
  2628. else:
  2629. cursor = self.ui.code_editor.textCursor()
  2630. cursor.beginEditBlock()
  2631. qc = self.ui.code_editor.textCursor()
  2632. if qc.hasSelection():
  2633. qc.insertText(new)
  2634. # Mark end of undo block
  2635. cursor.endEditBlock()
  2636. def on_new_geometry(self):
  2637. def initialize(obj, self):
  2638. obj.multitool = False
  2639. self.new_object('geometry', 'new_g', initialize)
  2640. self.plot_all()
  2641. def on_delete(self):
  2642. """
  2643. Delete the currently selected FlatCAMObjs.
  2644. :return: None
  2645. """
  2646. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  2647. # a geometry object before we update it.
  2648. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  2649. if self.collection.get_active():
  2650. self.log.debug("on_delete()")
  2651. self.report_usage("on_delete")
  2652. while (self.collection.get_active()):
  2653. self.delete_first_selected()
  2654. self.inform.emit("Object(s) deleted ...")
  2655. # make sure that the selection shape is deleted, too
  2656. self.delete_selection_shape()
  2657. else:
  2658. self.inform.emit("Failed. No object(s) selected...")
  2659. else:
  2660. self.inform.emit("Save the work in Editor and try again ...")
  2661. def on_set_origin(self):
  2662. """
  2663. Set the origin to the left mouse click position
  2664. :return: None
  2665. """
  2666. #display the message for the user
  2667. #and ask him to click on the desired position
  2668. self.inform.emit('Click to set the origin ...')
  2669. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  2670. def on_jump_to(self):
  2671. """
  2672. Jump to a location by setting the mouse cursor location
  2673. :return:
  2674. """
  2675. dia_box = Dialog_box(title="Jump to Coordinates", label="Enter the coordinates in format X,Y:")
  2676. if dia_box.ok is True:
  2677. try:
  2678. location = eval(dia_box.location)
  2679. if not isinstance(location, tuple):
  2680. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  2681. return
  2682. except:
  2683. return
  2684. else:
  2685. return
  2686. self.plotcanvas.fit_center(loc=location)
  2687. cursor = QtGui.QCursor()
  2688. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  2689. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  2690. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  2691. self.inform.emit("Done.")
  2692. def on_copy_object(self):
  2693. def initialize(obj_init, app):
  2694. obj_init.solid_geometry = obj.solid_geometry
  2695. try:
  2696. if obj.tools:
  2697. obj_init.tools = obj.tools
  2698. except Exception as e:
  2699. log.debug("on_copy_object() --> %s" % str(e))
  2700. def initialize_excellon(obj_init, app):
  2701. obj_init.tools = obj.tools
  2702. # drills are offset, so they need to be deep copied
  2703. obj_init.drills = deepcopy(obj.drills)
  2704. # slots are offset, so they need to be deep copied
  2705. obj_init.slots = deepcopy(obj.slots)
  2706. obj_init.create_geometry()
  2707. for obj in self.collection.get_selected():
  2708. obj_name = obj.options["name"]
  2709. try:
  2710. if isinstance(obj, FlatCAMExcellon):
  2711. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  2712. elif isinstance(obj,FlatCAMGerber):
  2713. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  2714. elif isinstance(obj,FlatCAMGeometry):
  2715. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  2716. except Exception as e:
  2717. return "Operation failed: %s" % str(e)
  2718. def on_copy_object2(self, custom_name):
  2719. def initialize_geometry(obj_init, app):
  2720. obj_init.solid_geometry = obj.solid_geometry
  2721. try:
  2722. if obj.tools:
  2723. obj_init.tools = obj.tools
  2724. except Exception as e:
  2725. log.debug("on_copy_object2() --> %s" % str(e))
  2726. def initialize_gerber(obj_init, app):
  2727. obj_init.solid_geometry = obj.solid_geometry
  2728. obj_init.apertures = deepcopy(obj.apertures)
  2729. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  2730. def initialize_excellon(obj_init, app):
  2731. obj_init.tools = obj.tools
  2732. # drills are offset, so they need to be deep copied
  2733. obj_init.drills = deepcopy(obj.drills)
  2734. # slots are offset, so they need to be deep copied
  2735. obj_init.slots = deepcopy(obj.slots)
  2736. obj_init.create_geometry()
  2737. for obj in self.collection.get_selected():
  2738. obj_name = obj.options["name"]
  2739. try:
  2740. if isinstance(obj, FlatCAMExcellon):
  2741. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  2742. elif isinstance(obj,FlatCAMGerber):
  2743. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  2744. elif isinstance(obj,FlatCAMGeometry):
  2745. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  2746. except Exception as e:
  2747. return "Operation failed: %s" % str(e)
  2748. def on_rename_object(self, text):
  2749. named_obj = self.collection.get_active()
  2750. for obj in named_obj:
  2751. if obj is list:
  2752. self.on_rename_object(text)
  2753. else:
  2754. try:
  2755. obj.options['name'] = text
  2756. except:
  2757. log.warning("Could not rename the object in the list")
  2758. def on_copy_object_as_geometry(self):
  2759. def initialize(obj_init, app):
  2760. obj_init.solid_geometry = obj.solid_geometry
  2761. if obj.tools:
  2762. obj_init.tools = obj.tools
  2763. def initialize_excellon(obj, app):
  2764. objs = self.collection.get_selected()
  2765. FlatCAMGeometry.merge(objs, obj)
  2766. for obj in self.collection.get_selected():
  2767. obj_name = obj.options["name"]
  2768. try:
  2769. if isinstance(obj, FlatCAMExcellon):
  2770. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  2771. else:
  2772. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  2773. except Exception as e:
  2774. return "Operation failed: %s" % str(e)
  2775. def on_set_zero_click(self, event):
  2776. #this function will be available only for mouse left click
  2777. pos =[]
  2778. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  2779. if event.button == 1:
  2780. if self.grid_status() == True:
  2781. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2782. else:
  2783. pos = pos_canvas
  2784. x = 0 - pos[0]
  2785. y = 0 - pos[1]
  2786. for obj in self.collection.get_list():
  2787. obj.offset((x,y))
  2788. self.object_changed.emit(obj)
  2789. # obj.plot()
  2790. self.plot_all()
  2791. self.inform.emit('[success] Origin set ...')
  2792. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  2793. def on_selectall(self):
  2794. # delete the possible selection box around a possible selected object
  2795. self.delete_selection_shape()
  2796. for name in self.collection.get_names():
  2797. self.collection.set_active(name)
  2798. curr_sel_obj = self.collection.get_by_name(name)
  2799. # create the selection box around the selected object
  2800. self.draw_selection_shape(curr_sel_obj)
  2801. def on_preferences(self):
  2802. # add the tab if it was closed
  2803. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  2804. # delete the absolute and relative position and messages in the infobar
  2805. self.ui.position_label.setText("")
  2806. self.ui.rel_position_label.setText("")
  2807. # Switch plot_area to preferences page
  2808. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  2809. self.ui.show()
  2810. def on_flipy(self):
  2811. obj_list = self.collection.get_selected()
  2812. xminlist = []
  2813. yminlist = []
  2814. xmaxlist = []
  2815. ymaxlist = []
  2816. if not obj_list:
  2817. self.inform.emit("[warning_notcl] No object selected.")
  2818. msg = "Please Select an object to flip!"
  2819. warningbox = QtWidgets.QMessageBox()
  2820. warningbox.setText(msg)
  2821. warningbox.setWindowTitle("Warning ...")
  2822. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2823. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2824. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2825. warningbox.exec_()
  2826. else:
  2827. try:
  2828. # first get a bounding box to fit all
  2829. for obj in obj_list:
  2830. xmin, ymin, xmax, ymax = obj.bounds()
  2831. xminlist.append(xmin)
  2832. yminlist.append(ymin)
  2833. xmaxlist.append(xmax)
  2834. ymaxlist.append(ymax)
  2835. # get the minimum x,y and maximum x,y for all objects selected
  2836. xminimal = min(xminlist)
  2837. yminimal = min(yminlist)
  2838. xmaximal = max(xmaxlist)
  2839. ymaximal = max(ymaxlist)
  2840. px = 0.5 * (xminimal + xmaximal)
  2841. py = 0.5 * (yminimal + ymaximal)
  2842. # execute mirroring
  2843. for obj in obj_list:
  2844. obj.mirror('X', [px, py])
  2845. obj.plot()
  2846. self.object_changed.emit(obj)
  2847. except Exception as e:
  2848. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2849. return
  2850. def on_flipx(self):
  2851. obj_list = self.collection.get_selected()
  2852. xminlist = []
  2853. yminlist = []
  2854. xmaxlist = []
  2855. ymaxlist = []
  2856. if not obj_list:
  2857. self.inform.emit("[warning_notcl] No object selected.")
  2858. msg = "Please Select an object to flip!"
  2859. warningbox = QtWidgets.QMessageBox()
  2860. warningbox.setText(msg)
  2861. warningbox.setWindowTitle("Warning ...")
  2862. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2863. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2864. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2865. warningbox.exec_()
  2866. else:
  2867. try:
  2868. # first get a bounding box to fit all
  2869. for obj in obj_list:
  2870. xmin, ymin, xmax, ymax = obj.bounds()
  2871. xminlist.append(xmin)
  2872. yminlist.append(ymin)
  2873. xmaxlist.append(xmax)
  2874. ymaxlist.append(ymax)
  2875. # get the minimum x,y and maximum x,y for all objects selected
  2876. xminimal = min(xminlist)
  2877. yminimal = min(yminlist)
  2878. xmaximal = max(xmaxlist)
  2879. ymaximal = max(ymaxlist)
  2880. px = 0.5 * (xminimal + xmaximal)
  2881. py = 0.5 * (yminimal + ymaximal)
  2882. # execute mirroring
  2883. for obj in obj_list:
  2884. obj.mirror('Y', [px, py])
  2885. obj.plot()
  2886. self.object_changed.emit(obj)
  2887. except Exception as e:
  2888. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2889. return
  2890. def on_rotate(self, silent=False, preset=None):
  2891. obj_list = self.collection.get_selected()
  2892. xminlist = []
  2893. yminlist = []
  2894. xmaxlist = []
  2895. ymaxlist = []
  2896. if not obj_list:
  2897. self.inform.emit("[warning_notcl] No object selected.")
  2898. msg = "Please Select an object to rotate!"
  2899. warningbox = QtWidgets.QMessageBox()
  2900. warningbox.setText(msg)
  2901. warningbox.setWindowTitle("Warning ...")
  2902. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2903. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2904. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2905. warningbox.exec_()
  2906. else:
  2907. if silent is False:
  2908. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2909. min=-360, max=360, decimals=3)
  2910. num, ok = rotatebox.get_value()
  2911. else:
  2912. num = preset
  2913. ok = True
  2914. if ok:
  2915. try:
  2916. # first get a bounding box to fit all
  2917. for obj in obj_list:
  2918. xmin, ymin, xmax, ymax = obj.bounds()
  2919. xminlist.append(xmin)
  2920. yminlist.append(ymin)
  2921. xmaxlist.append(xmax)
  2922. ymaxlist.append(ymax)
  2923. # get the minimum x,y and maximum x,y for all objects selected
  2924. xminimal = min(xminlist)
  2925. yminimal = min(yminlist)
  2926. xmaximal = max(xmaxlist)
  2927. ymaximal = max(ymaxlist)
  2928. px = 0.5 * (xminimal + xmaximal)
  2929. py = 0.5 * (yminimal + ymaximal)
  2930. for sel_obj in obj_list:
  2931. sel_obj.rotate(-num, point=(px, py))
  2932. sel_obj.plot()
  2933. self.object_changed.emit(sel_obj)
  2934. except Exception as e:
  2935. self.inform.emit("[error_notcl] Due of %s, rotation movement was not executed." % str(e))
  2936. return
  2937. def on_skewx(self):
  2938. obj_list = self.collection.get_selected()
  2939. xminlist = []
  2940. yminlist = []
  2941. if not obj_list:
  2942. self.inform.emit("[warning_notcl] No object selected.")
  2943. msg = "Please Select an object to skew/shear!"
  2944. warningbox = QtWidgets.QMessageBox()
  2945. warningbox.setText(msg)
  2946. warningbox.setWindowTitle("Warning ...")
  2947. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2948. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2949. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2950. warningbox.exec_()
  2951. else:
  2952. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2953. min=-360, max=360, decimals=3)
  2954. num, ok = skewxbox.get_value()
  2955. if ok:
  2956. # first get a bounding box to fit all
  2957. for obj in obj_list:
  2958. xmin, ymin, xmax, ymax = obj.bounds()
  2959. xminlist.append(xmin)
  2960. yminlist.append(ymin)
  2961. # get the minimum x,y and maximum x,y for all objects selected
  2962. xminimal = min(xminlist)
  2963. yminimal = min(yminlist)
  2964. for obj in obj_list:
  2965. obj.skew(num, 0, point=(xminimal, yminimal))
  2966. obj.plot()
  2967. self.object_changed.emit(obj)
  2968. def on_skewy(self):
  2969. obj_list = self.collection.get_selected()
  2970. xminlist = []
  2971. yminlist = []
  2972. if not obj_list:
  2973. self.inform.emit("[warning_notcl] No object selected.")
  2974. msg = "Please Select an object to skew/shear!"
  2975. warningbox = QtWidgets.QMessageBox()
  2976. warningbox.setText(msg)
  2977. warningbox.setWindowTitle("Warning ...")
  2978. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2979. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2980. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2981. warningbox.exec_()
  2982. else:
  2983. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2984. min=-360, max=360, decimals=3)
  2985. num, ok = skewybox.get_value()
  2986. if ok:
  2987. # first get a bounding box to fit all
  2988. for obj in obj_list:
  2989. xmin, ymin, xmax, ymax = obj.bounds()
  2990. xminlist.append(xmin)
  2991. yminlist.append(ymin)
  2992. # get the minimum x,y and maximum x,y for all objects selected
  2993. xminimal = min(xminlist)
  2994. yminimal = min(yminlist)
  2995. for obj in obj_list:
  2996. obj.skew(0, num, point=(xminimal, yminimal))
  2997. obj.plot()
  2998. self.object_changed.emit(obj)
  2999. def delete_first_selected(self):
  3000. # Keep this for later
  3001. try:
  3002. name = self.collection.get_active().options["name"]
  3003. except AttributeError:
  3004. self.log.debug("Nothing selected for deletion")
  3005. return
  3006. # Remove plot
  3007. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3008. # self.plotcanvas.auto_adjust_axes()
  3009. # Clear form
  3010. self.setup_component_editor()
  3011. # Remove from dictionary
  3012. self.collection.delete_active()
  3013. self.inform.emit("Object deleted: %s" % name)
  3014. def on_plots_updated(self):
  3015. """
  3016. Callback used to report when the plots have changed.
  3017. Adjust axes and zooms to fit.
  3018. :return: None
  3019. """
  3020. # self.plotcanvas.auto_adjust_axes()
  3021. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3022. self.on_zoom_fit(None)
  3023. # TODO: Rework toolbar 'clear', 'replot' functions
  3024. def on_toolbar_replot(self):
  3025. """
  3026. Callback for toolbar button. Re-plots all objects.
  3027. :return: None
  3028. """
  3029. self.report_usage("on_toolbar_replot")
  3030. self.log.debug("on_toolbar_replot()")
  3031. try:
  3032. self.collection.get_active().read_form()
  3033. except AttributeError:
  3034. self.log.debug("on_toolbar_replot(): AttributeError")
  3035. pass
  3036. self.plot_all()
  3037. def on_row_activated(self, index):
  3038. if index.isValid():
  3039. if index.internalPointer().parent_item != self.collection.root_item:
  3040. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3041. def grid_status(self):
  3042. if self.ui.grid_snap_btn.isChecked():
  3043. return 1
  3044. else:
  3045. return 0
  3046. def on_key_over_plot(self, event):
  3047. """
  3048. Callback for the key pressed event when the canvas is focused. Keyboard
  3049. shortcuts are handled here. So far, these are the shortcuts:
  3050. ========== ============================================
  3051. Key Action
  3052. ========== ============================================
  3053. '1' Zoom-fit. Fits the axes limits to the data.
  3054. '2' Zoom-out.
  3055. '3' Zoom-in.
  3056. 'ctrl+m' Toggle on-off the measuring tool.
  3057. ========== ============================================
  3058. :param event: Ignored.
  3059. :return: None
  3060. """
  3061. self.key_modifiers = QtWidgets.QApplication.keyboardModifiers()
  3062. if self.key_modifiers == QtCore.Qt.ControlModifier:
  3063. if event.key == 'A':
  3064. self.on_selectall()
  3065. if event.key == 'C':
  3066. self.on_copy_object()
  3067. if event.key == 'E':
  3068. self.on_fileopenexcellon()
  3069. if event.key == 'G':
  3070. self.on_fileopengerber()
  3071. if event.key == 'N':
  3072. self.on_file_new_click()
  3073. if event.key == 'M':
  3074. self.measurement_tool.run()
  3075. if event.key == 'O':
  3076. self.on_file_openproject()
  3077. if event.key == 'S':
  3078. self.on_file_saveproject()
  3079. return
  3080. elif self.key_modifiers == QtCore.Qt.AltModifier:
  3081. # place holder for further shortcut key
  3082. if event.key == '1':
  3083. self.enable_all_plots()
  3084. if event.key == '2':
  3085. self.disable_all_plots()
  3086. if event.key == '3':
  3087. self.disable_other_plots()
  3088. if event.key == 'C':
  3089. self.calculator_tool.run()
  3090. if event.key == 'D':
  3091. self.dblsidedtool.run()
  3092. if event.key == 'L':
  3093. self.film_tool.run()
  3094. if event.key == 'N':
  3095. self.ncclear_tool.run()
  3096. if event.key == 'P':
  3097. self.paint_tool.run()
  3098. if event.key == 'R':
  3099. self.transform_tool.run()
  3100. if event.key == 'U':
  3101. self.cutout_tool.run()
  3102. if event.key == 'Z':
  3103. self.panelize_tool.run()
  3104. if event.key == 'F10':
  3105. self.on_fullscreen()
  3106. elif self.key_modifiers == QtCore.Qt.ShiftModifier:
  3107. # place holder for further shortcut key
  3108. if event.key == 'C':
  3109. self.on_copy_name()
  3110. # Toggle axis
  3111. if event.key == 'G':
  3112. self.on_toggle_axis()
  3113. # Open Preferences Window
  3114. if event.key == 'P':
  3115. self.on_preferences()
  3116. # Rotate Object by 90 degree CCW
  3117. if event.key == 'R':
  3118. self.on_rotate(silent=True, preset=-90)
  3119. # Run a Script
  3120. if event.key == 'S':
  3121. self.on_filerunscript()
  3122. # Toggle Workspace
  3123. if event.key == 'W':
  3124. self.on_workspace_menu()
  3125. # Skew on X axis
  3126. if event.key == 'X':
  3127. self.on_skewx()
  3128. # Skew on Y axis
  3129. if event.key == 'Y':
  3130. self.on_skewy()
  3131. return
  3132. else:
  3133. if event.key == 'F1':
  3134. webbrowser.open(self.manual_url)
  3135. return
  3136. if event.key == 'F2':
  3137. webbrowser.open(self.video_url)
  3138. return
  3139. if event.key == self.defaults['fit_key']: # 1
  3140. self.on_zoom_fit(None)
  3141. return
  3142. if event.key == self.defaults['zoom_out_key']: # 2
  3143. self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  3144. return
  3145. if event.key == self.defaults['zoom_in_key']: # 3
  3146. self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  3147. return
  3148. if event.key == 'Delete':
  3149. self.on_delete()
  3150. return
  3151. if event.key == 'Space':
  3152. if self.collection.get_active() is not None:
  3153. self.collection.get_active().ui.plot_cb.toggle()
  3154. self.delete_selection_shape()
  3155. if event.key == 'E':
  3156. self.object2editor()
  3157. if event.key == self.defaults['grid_toggle_key']: # G
  3158. self.ui.grid_snap_btn.trigger()
  3159. if event.key == 'J':
  3160. self.on_jump_to()
  3161. if event.key == 'L':
  3162. self.new_excellon_object()
  3163. if event.key == 'M':
  3164. self.move_tool.toggle()
  3165. return
  3166. if event.key == 'N':
  3167. self.on_new_geometry()
  3168. if event.key == 'O':
  3169. self.on_set_origin()
  3170. if event.key == 'P':
  3171. self.properties_tool.run()
  3172. if event.key == 'Q':
  3173. self.on_toggle_units_click()
  3174. if event.key == 'R':
  3175. self.on_rotate(silent=True, preset=90)
  3176. if event.key == 'S':
  3177. self.on_toggle_shell()
  3178. if event.key == 'V':
  3179. self.on_zoom_fit(None)
  3180. if event.key == 'X':
  3181. self.on_flipx()
  3182. if event.key == 'Y':
  3183. self.on_flipy()
  3184. if event.key == '`':
  3185. self.on_shortcut_list()
  3186. def on_key_release_over_plot(self, event):
  3187. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3188. if modifiers == QtCore.Qt.ControlModifier:
  3189. return
  3190. elif modifiers == QtCore.Qt.AltModifier:
  3191. # place holder for further shortcut key
  3192. return
  3193. elif modifiers == QtCore.Qt.ShiftModifier:
  3194. # place holder for further shortcut key
  3195. return
  3196. else:
  3197. return
  3198. def on_shortcut_list(self):
  3199. msg = '''<b>Shortcut list</b><br>
  3200. <br>
  3201. <b>~:</b> Show Shortcut List<br>
  3202. <br>
  3203. <b>1:</b> Zoom Fit<br>
  3204. <b>2:</b> Zoom Out<br>
  3205. <b>3:</b> Zoom In<br>
  3206. <b>A:</b> Draw an Arc (when in Edit Mode)<br>
  3207. <b>C:</b> Copy Geo Item (when in Edit Mode)<br>
  3208. <b>E:</b> Edit Object (if selected)<br>
  3209. <b>G:</b> Grid On/Off<br>
  3210. <b>J:</b> Jump to Coordinates<br>
  3211. <b>L:</b> New Excellon<br>
  3212. <b>M:</b> Move Obj<br>
  3213. <b>M:</b> Move Geo Item (when in Edit Mode)<br>
  3214. <b>N:</b> New Geometry<br>
  3215. <b>N:</b> Draw a Polygon (when in Edit Mode)<br>
  3216. <b>O:</b> Set Origin<br>
  3217. <b>O:</b> Draw a Circle (when in Edit Mode)<br>
  3218. <b>Q:</b> Change Units<br>
  3219. <b>P:</b> Open Properties Tool<br>
  3220. <b>P:</b> Draw a Path (when in Edit Mode)<br>
  3221. <b>R:</b> Rotate by 90 degree CW<br>
  3222. <b>R:</b> Draw Rectangle (when in Edit Mode)<br>
  3223. <b>S:</b> Shell Toggle<br>
  3224. <b>V:</b> View Fit<br>
  3225. <b>X:</b> Flip on X_axis<br>
  3226. <b>Y:</b> Flip on Y_axis<br>
  3227. <br>
  3228. <b>Space:</b> En(Dis)able Obj Plot<br>
  3229. <b>CTRL+A:</b> Select All<br>
  3230. <b>CTRL+C:</b> Copy Obj<br>
  3231. <b>CTRL+E:</b> Open Excellon File<br>
  3232. <b>CTRL+G:</b> Open Gerber File<br>
  3233. <b>CTRL+N:</b> New Project<br>
  3234. <b>CTRL+M:</b> Measurement Tool<br>
  3235. <b>CTRL+O:</b> Open Project<br>
  3236. <b>CTRL+S:</b> Save Project As<br>
  3237. <b>CTRL+S:</b> Save Object and Exit Editor (when in Edit Mode)<br>
  3238. <br>
  3239. <b>SHIFT+C:</b> Copy Obj_Name<br>
  3240. <b>SHIFT+G:</b> Toggle the axis<br>
  3241. <b>SHIFT+P:</b> Open Preferences Window<br>
  3242. <b>SHIFT+R:</b> Rotate by 90 degree CCW<br>
  3243. <b>SHIFT+S:</b> Run a Script<br>
  3244. <b>SHIFT+W:</b> Toggle the workspace<br>
  3245. <b>SHIFT+X:</b> Skew on X axis<br>
  3246. <b>SHIFT+Y:</b> Skew on Y axis<br>
  3247. <br>
  3248. <b>ALT+C:</b> Calculators Tool<br>
  3249. <b>ALT+D:</b> 2-Sided PCB Tool<br>
  3250. <b>ALT+L:</b> Film PCB Tool<br>
  3251. <b>ALT+N:</b> Non-Copper Clearing Tool<br>
  3252. <b>ALT+P:</b> Paint Area Tool<br>
  3253. <b>ALT+R:</b> Transformation Tool<br>
  3254. <b>ALT+U:</b> Cutout PCB Tool<br>
  3255. <b>ALT+F10:</b> Toggle Full Screen<br>
  3256. <br>
  3257. <b>F1:</b> Open Online Manual<br>
  3258. <b>F2:</b> Open Online Tutorials<br>
  3259. <b>Del:</b> Delete Obj
  3260. '''
  3261. helpbox = QtWidgets.QMessageBox()
  3262. helpbox.setText(msg)
  3263. helpbox.setWindowTitle("Help")
  3264. helpbox.setWindowIcon(QtGui.QIcon('share/help.png'))
  3265. helpbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3266. helpbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3267. helpbox.exec_()
  3268. def on_copy_name(self):
  3269. obj = self.collection.get_active()
  3270. try:
  3271. name = obj.options["name"]
  3272. except AttributeError:
  3273. log.debug("on_copy_name() --> No object selected to copy it's name")
  3274. self.inform.emit("[warning_notcl]No object selected to copy it's name")
  3275. return
  3276. self.clipboard.setText(name)
  3277. self.inform.emit("Name copied on clipboard ...")
  3278. def on_mouse_click_over_plot(self, event):
  3279. """
  3280. Callback for the mouse click event over the plot. This event is generated
  3281. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3282. For details, see: http://matplotlib.org/users/event_handling.html
  3283. Default actions are:
  3284. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  3285. :param event: Contains information about the event, like which button
  3286. was clicked, the pixel coordinates and the axes coordinates.
  3287. :return: None
  3288. """
  3289. self.pos = []
  3290. # So it can receive key presses
  3291. self.plotcanvas.vispy_canvas.native.setFocus()
  3292. # Set the mouse button for panning
  3293. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3294. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3295. if self.grid_status() == True:
  3296. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3297. self.app_cursor.enabled = True
  3298. else:
  3299. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3300. self.app_cursor.enabled = False
  3301. try:
  3302. App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  3303. event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  3304. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3305. if event.button == 1:
  3306. # Reset here the relative coordinates so there is a new reference on the click position
  3307. if self.rel_point1 is None:
  3308. self.rel_point1 = self.pos
  3309. else:
  3310. self.rel_point2 = copy(self.rel_point1)
  3311. self.rel_point1 = self.pos
  3312. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3313. if modifiers == QtCore.Qt.ShiftModifier:
  3314. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3315. return
  3316. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3317. # and if it's not selected then it will be selected
  3318. if modifiers == QtCore.Qt.ControlModifier:
  3319. # If there is no active command (self.command_active is None) then we check if we clicked on
  3320. # a object by checking the bounding limits against mouse click position
  3321. if self.command_active is None:
  3322. self.select_objects(key='CTRL')
  3323. else:
  3324. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3325. # checking the bounding limits against mouse click position
  3326. if self.command_active is None:
  3327. self.select_objects()
  3328. self.on_mouse_move_over_plot(event, origin_click=True)
  3329. except Exception as e:
  3330. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3331. def on_double_click_over_plot(self, event):
  3332. # make double click work only for the LMB
  3333. if event.button == 1:
  3334. if not self.collection.get_selected():
  3335. pass
  3336. else:
  3337. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3338. #delete the selection shape(S) as it may be in the way
  3339. self.delete_selection_shape()
  3340. def on_mouse_move_over_plot(self, event, origin_click=None):
  3341. """
  3342. Callback for the mouse motion event over the plot. This event is generated
  3343. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3344. For details, see: http://matplotlib.org/users/event_handling.html
  3345. :param event: Contains information about the event.
  3346. :param origin_click
  3347. :return: None
  3348. """
  3349. # So it can receive key presses
  3350. self.plotcanvas.vispy_canvas.native.setFocus()
  3351. self.pos_jump = event.pos
  3352. if origin_click is True:
  3353. pass
  3354. else:
  3355. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3356. if event.button == 2:
  3357. self.panning_action = True
  3358. return
  3359. else:
  3360. self.panning_action = False
  3361. if self.rel_point1 is not None:
  3362. try: # May fail in case mouse not within axes
  3363. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3364. if self.grid_status():
  3365. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3366. self.app_cursor.enabled = True
  3367. # Update cursor
  3368. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3369. else:
  3370. pos = (pos_canvas[0], pos_canvas[1])
  3371. self.app_cursor.enabled = False
  3372. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3373. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3374. dx = pos[0] - self.rel_point1[0]
  3375. dy = pos[1] - self.rel_point1[1]
  3376. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3377. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3378. self.mouse = [pos[0], pos[1]]
  3379. # if the mouse is moved and the LMB is clicked then the action is a selection
  3380. if event.is_dragging == 1 and event.button == 1:
  3381. self.delete_selection_shape()
  3382. if dx < 0:
  3383. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3384. face_color=self.defaults['global_alt_sel_fill'])
  3385. self.selection_type = False
  3386. else:
  3387. self.draw_moving_selection_shape(self.pos, pos)
  3388. self.selection_type = True
  3389. # delete the status message on mouse move
  3390. # self.inform.emit("")
  3391. except:
  3392. self.ui.position_label.setText("")
  3393. self.ui.rel_position_label.setText("")
  3394. self.mouse = None
  3395. def on_mouse_click_release_over_plot(self, event):
  3396. """
  3397. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3398. and has been registered in ''self.__init__()''.
  3399. :param event: contains information about the event.
  3400. :return:
  3401. """
  3402. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3403. if self.grid_status():
  3404. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3405. else:
  3406. pos = (pos_canvas[0], pos_canvas[1])
  3407. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3408. # canvas menu
  3409. try:
  3410. if event.button == 2: # right click
  3411. if self.panning_action is True:
  3412. self.panning_action = False
  3413. else:
  3414. self.cursor = QtGui.QCursor()
  3415. self.ui.popMenu.popup(self.cursor.pos())
  3416. except Exception as e:
  3417. log.warning("Error: %s" % str(e))
  3418. return
  3419. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3420. # selection and then select a type of selection ("enclosing" or "touching")
  3421. try:
  3422. if event.button == 1: # left click
  3423. if self.selection_type is not None:
  3424. self.selection_area_handler(self.pos, pos, self.selection_type)
  3425. self.selection_type = None
  3426. except Exception as e:
  3427. log.warning("Error: %s" % str(e))
  3428. return
  3429. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3430. """
  3431. :param start_pos: mouse position when the selection LMB click was done
  3432. :param end_pos: mouse position when the left mouse button is released
  3433. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3434. :return:
  3435. """
  3436. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3437. self.delete_selection_shape()
  3438. for obj in self.collection.get_list():
  3439. try:
  3440. # select the object(s) only if it is enabled (plotted)
  3441. if obj.options['plot']:
  3442. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3443. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3444. if sel_type is True:
  3445. if poly_obj.within(poly_selection):
  3446. # create the selection box around the selected object
  3447. self.draw_selection_shape(obj)
  3448. self.collection.set_active(obj.options['name'])
  3449. else:
  3450. if poly_selection.intersects(poly_obj):
  3451. # create the selection box around the selected object
  3452. self.draw_selection_shape(obj)
  3453. self.collection.set_active(obj.options['name'])
  3454. except:
  3455. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3456. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3457. # In this case poly_obj creation (see above) will fail
  3458. pass
  3459. def select_objects(self, key=None):
  3460. # list where we store the overlapped objects under our mouse left click position
  3461. objects_under_the_click_list = []
  3462. # Populate the list with the overlapped objects on the click position
  3463. curr_x, curr_y = self.pos
  3464. for obj in self.all_objects_list:
  3465. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3466. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3467. if obj.options['name'] not in objects_under_the_click_list:
  3468. if obj.options['plot']:
  3469. # add objects to the objects_under_the_click list only if the object is plotted
  3470. # (active and not disabled)
  3471. objects_under_the_click_list.append(obj.options['name'])
  3472. try:
  3473. # If there is no element in the overlapped objects list then make everyone inactive
  3474. # because we selected "nothing"
  3475. if not objects_under_the_click_list:
  3476. self.collection.set_all_inactive()
  3477. # delete the possible selection box around a possible selected object
  3478. self.delete_selection_shape()
  3479. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3480. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3481. else:
  3482. # case when there is only an object under the click and we toggle it
  3483. if len(objects_under_the_click_list) == 1:
  3484. if self.collection.get_active() is None :
  3485. self.collection.set_active(objects_under_the_click_list[0])
  3486. # create the selection box around the selected object
  3487. curr_sel_obj = self.collection.get_active()
  3488. self.draw_selection_shape(curr_sel_obj)
  3489. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3490. self.collection.set_all_inactive()
  3491. self.delete_selection_shape()
  3492. self.collection.set_active(objects_under_the_click_list[0])
  3493. # create the selection box around the selected object
  3494. curr_sel_obj = self.collection.get_active()
  3495. self.draw_selection_shape(curr_sel_obj)
  3496. else:
  3497. self.collection.set_all_inactive()
  3498. self.delete_selection_shape()
  3499. else:
  3500. # If there is no selected object
  3501. # make active the first element of the overlapped objects list
  3502. if self.collection.get_active() is None:
  3503. self.collection.set_active(objects_under_the_click_list[0])
  3504. name_sel_obj = self.collection.get_active().options['name']
  3505. # In case that there is a selected object but it is not in the overlapped object list
  3506. # make that object inactive and activate the first element in the overlapped object list
  3507. if name_sel_obj not in objects_under_the_click_list:
  3508. self.collection.set_inactive(name_sel_obj)
  3509. name_sel_obj = objects_under_the_click_list[0]
  3510. self.collection.set_active(name_sel_obj)
  3511. else:
  3512. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3513. self.collection.set_all_inactive()
  3514. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) % len(objects_under_the_click_list)])
  3515. curr_sel_obj = self.collection.get_active()
  3516. # delete the possible selection box around a possible selected object
  3517. self.delete_selection_shape()
  3518. # create the selection box around the selected object
  3519. self.draw_selection_shape(curr_sel_obj)
  3520. # for obj in self.collection.get_list():
  3521. # obj.plot()
  3522. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3523. # TODO: on selected objects change the object colors and do not draw the selection box
  3524. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3525. except Exception as e:
  3526. log.error("[error] Something went bad. %s" % str(e))
  3527. return
  3528. def delete_selection_shape(self):
  3529. self.move_tool.sel_shapes.clear()
  3530. self.move_tool.sel_shapes.redraw()
  3531. def draw_selection_shape(self, sel_obj):
  3532. """
  3533. :param sel_obj: the object for which the selection shape must be drawn
  3534. :return:
  3535. """
  3536. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3537. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3538. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3539. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3540. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3541. #blue_t = Color('blue')
  3542. blue_t = Color(self.defaults['global_sel_fill'])
  3543. blue_t.alpha = 0.3
  3544. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3545. face_color=blue_t, update=True, layer=0, tolerance=None))
  3546. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3547. """
  3548. :param old_coords: old coordinates
  3549. :param coords: new coordinates
  3550. :return:
  3551. """
  3552. if 'color' in kwargs:
  3553. color = kwargs['color']
  3554. else:
  3555. color = self.defaults['global_sel_line']
  3556. if 'face_color' in kwargs:
  3557. face_color = kwargs['face_color']
  3558. else:
  3559. face_color = self.defaults['global_sel_fill']
  3560. x0, y0 = old_coords
  3561. x1, y1 = coords
  3562. pt1 = (x0, y0)
  3563. pt2 = (x1, y0)
  3564. pt3 = (x1, y1)
  3565. pt4 = (x0, y1)
  3566. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3567. color_t = Color(face_color)
  3568. color_t.alpha = 0.3
  3569. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3570. layer=0, tolerance=None)
  3571. def on_file_new_click(self):
  3572. if self.collection.get_list():
  3573. msgbox = QtWidgets.QMessageBox()
  3574. # msgbox.setText("<B>Save changes ...</B>")
  3575. msgbox.setText("There are files/objects opened in FlatCAM.\n"
  3576. "Creating a New project will delete them.\n"
  3577. "Do you want to Save the project?")
  3578. msgbox.setWindowTitle("Save changes")
  3579. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3580. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  3581. QtWidgets.QMessageBox.No)
  3582. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3583. response = msgbox.exec_()
  3584. if response == QtWidgets.QMessageBox.Yes:
  3585. self.on_file_saveprojectas()
  3586. elif response == QtWidgets.QMessageBox.Cancel:
  3587. return
  3588. self.on_file_new()
  3589. else:
  3590. self.on_file_new()
  3591. self.inform.emit("[success] New Project created...")
  3592. def on_file_new(self):
  3593. """
  3594. Callback for menu item File->New. Returns the application to its
  3595. startup state. This method is thread-safe.
  3596. :return: None
  3597. """
  3598. self.report_usage("on_file_new")
  3599. # Remove everything from memory
  3600. App.log.debug("on_file_new()")
  3601. # Clear pool
  3602. self.clear_pool()
  3603. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3604. self.init_tcl()
  3605. self.delete_selection_shape()
  3606. self.collection.delete_all()
  3607. self.setup_component_editor()
  3608. # Clear project filename
  3609. self.project_filename = None
  3610. # Load the application defaults
  3611. self.load_defaults(filename='current_defaults')
  3612. # Re-fresh project options
  3613. self.on_options_app2project()
  3614. # Init Tools
  3615. self.init_tools()
  3616. # take the focus of the Notebook on Project Tab.
  3617. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3618. def obj_properties(self):
  3619. self.properties_tool.run()
  3620. def obj_move(self):
  3621. self.move_tool.run()
  3622. def on_fileopengerber(self):
  3623. """
  3624. File menu callback for opening a Gerber.
  3625. :return: None
  3626. """
  3627. self.report_usage("on_fileopengerber")
  3628. App.log.debug("on_fileopengerber()")
  3629. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3630. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3631. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3632. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3633. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3634. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3635. "Allegro Files (*.art);;" \
  3636. "Mentor Files (*.pho *.gdo);;" \
  3637. "All Files (*.*)"
  3638. try:
  3639. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber",
  3640. directory=self.get_last_folder(), filter=_filter_)
  3641. except TypeError:
  3642. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber", filter=_filter_)
  3643. filenames = [str(filename) for filename in filenames]
  3644. if len(filenames) == 0:
  3645. self.inform.emit("[warning_notcl]Open Gerber cancelled.")
  3646. else:
  3647. for filename in filenames:
  3648. if filename != '':
  3649. self.worker_task.emit({'fcn': self.open_gerber,
  3650. 'params': [filename]})
  3651. def on_fileopengerber_follow(self):
  3652. """
  3653. File menu callback for opening a Gerber.
  3654. :return: None
  3655. """
  3656. self.report_usage("on_fileopengerber_follow")
  3657. App.log.debug("on_fileopengerber_follow()")
  3658. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3659. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3660. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3661. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3662. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3663. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3664. "Allegro Files (*.art);;" \
  3665. "Mentor Files (*.pho *.gdo);;" \
  3666. "All Files (*.*)"
  3667. try:
  3668. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow",
  3669. directory=self.get_last_folder(), filter=_filter_)
  3670. except TypeError:
  3671. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow", filter=_filter_)
  3672. # The Qt methods above will return a QString which can cause problems later.
  3673. # So far json.dump() will fail to serialize it.
  3674. # TODO: Improve the serialization methods and remove this fix.
  3675. filename = str(filename)
  3676. follow = True
  3677. if filename == "":
  3678. self.inform.emit("[warning_notcl]Open Gerber-Follow cancelled.")
  3679. else:
  3680. self.worker_task.emit({'fcn': self.open_gerber,
  3681. 'params': [filename, follow]})
  3682. def on_fileopenexcellon(self):
  3683. """
  3684. File menu callback for opening an Excellon file.
  3685. :return: None
  3686. """
  3687. self.report_usage("on_fileopenexcellon")
  3688. App.log.debug("on_fileopenexcellon()")
  3689. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  3690. "All Files (*.*)"
  3691. try:
  3692. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon",
  3693. directory=self.get_last_folder(), filter=_filter_)
  3694. except TypeError:
  3695. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon", filter=_filter_)
  3696. filenames = [str(filename) for filename in filenames]
  3697. if len(filenames) == 0:
  3698. self.inform.emit("[warning_notcl]Open Excellon cancelled.")
  3699. else:
  3700. for filename in filenames:
  3701. if filename != '':
  3702. self.worker_task.emit({'fcn': self.open_excellon,
  3703. 'params': [filename]})
  3704. def on_fileopengcode(self):
  3705. """
  3706. File menu call back for opening gcode.
  3707. :return: None
  3708. """
  3709. self.report_usage("on_fileopengcode")
  3710. App.log.debug("on_fileopengcode()")
  3711. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  3712. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  3713. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  3714. "All Files (*.*)"
  3715. try:
  3716. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code",
  3717. directory=self.get_last_folder(), filter=_filter_)
  3718. except TypeError:
  3719. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code", filter=_filter_)
  3720. filenames = [str(filename) for filename in filenames]
  3721. if len(filenames) == 0:
  3722. self.inform.emit("[warning_notcl]Open G-Code cancelled.")
  3723. else:
  3724. for filename in filenames:
  3725. if filename != '':
  3726. self.worker_task.emit({'fcn': self.open_gcode,
  3727. 'params': [filename]})
  3728. def on_file_openproject(self):
  3729. """
  3730. File menu callback for opening a project.
  3731. :return: None
  3732. """
  3733. self.report_usage("on_file_openproject")
  3734. App.log.debug("on_file_openproject()")
  3735. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  3736. try:
  3737. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  3738. directory=self.get_last_folder(), filter=_filter_)
  3739. except TypeError:
  3740. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  3741. # The Qt methods above will return a QString which can cause problems later.
  3742. # So far json.dump() will fail to serialize it.
  3743. # TODO: Improve the serialization methods and remove this fix.
  3744. filename = str(filename)
  3745. if filename == "":
  3746. self.inform.emit("[warning_notcl]Open Project cancelled.")
  3747. else:
  3748. # self.worker_task.emit({'fcn': self.open_project,
  3749. # 'params': [filename]})
  3750. # The above was failing because open_project() is not
  3751. # thread safe. The new_project()
  3752. self.open_project(filename)
  3753. def on_file_exportsvg(self):
  3754. """
  3755. Callback for menu item File->Export SVG.
  3756. :return: None
  3757. """
  3758. self.report_usage("on_file_exportsvg")
  3759. App.log.debug("on_file_exportsvg()")
  3760. obj = self.collection.get_active()
  3761. if obj is None:
  3762. self.inform.emit("WARNING: No object selected.")
  3763. msg = "Please Select a Geometry object to export"
  3764. msgbox = QtWidgets.QMessageBox()
  3765. msgbox.setInformativeText(msg)
  3766. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3767. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3768. msgbox.exec_()
  3769. return
  3770. # Check for more compatible types and add as required
  3771. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  3772. and not isinstance(obj, FlatCAMExcellon)):
  3773. msg = "[error_notcl] Only Geometry, Gerber and CNCJob objects can be used."
  3774. msgbox = QtWidgets.QMessageBox()
  3775. msgbox.setInformativeText(msg)
  3776. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3777. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3778. msgbox.exec_()
  3779. return
  3780. name = self.collection.get_active().options["name"]
  3781. filter = "SVG File (*.svg);;All Files (*.*)"
  3782. try:
  3783. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG",
  3784. directory=self.get_last_save_folder(), filter=filter)
  3785. except TypeError:
  3786. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  3787. filename = str(filename)
  3788. if filename == "":
  3789. self.inform.emit("[warning_notcl]Export SVG cancelled.")
  3790. return
  3791. else:
  3792. self.export_svg(name, filename)
  3793. self.file_saved.emit("SVG", filename)
  3794. def on_file_exportpng(self):
  3795. self.report_usage("on_file_exportpng")
  3796. App.log.debug("on_file_exportpng()")
  3797. image = _screenshot()
  3798. data = np.asarray(image)
  3799. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  3800. self.inform.emit('[[warning_notcl]] Data must be a 3D array with last dimension 3 or 4')
  3801. return
  3802. filter = "PNG File (*.png);;All Files (*.*)"
  3803. try:
  3804. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image",
  3805. directory=self.get_last_save_folder(), filter=filter)
  3806. except TypeError:
  3807. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter)
  3808. filename = str(filename)
  3809. if filename == "":
  3810. self.inform.emit("Export PNG cancelled.")
  3811. return
  3812. else:
  3813. write_png(filename, data)
  3814. self.file_saved.emit("png", filename)
  3815. def on_file_exportexcellon(self, altium_format=None):
  3816. """
  3817. Callback for menu item File->Export SVG.
  3818. :return: None
  3819. """
  3820. self.report_usage("on_file_exportexcellon")
  3821. App.log.debug("on_file_exportexcellon()")
  3822. obj = self.collection.get_active()
  3823. if obj is None:
  3824. self.inform.emit("[warning_notcl] No object selected.")
  3825. msg = "Please Select an Excellon object to export"
  3826. msgbox = QtWidgets.QMessageBox()
  3827. msgbox.setInformativeText(msg)
  3828. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3829. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3830. msgbox.exec_()
  3831. return
  3832. # Check for more compatible types and add as required
  3833. if not isinstance(obj, FlatCAMExcellon):
  3834. msg = "[warning_notcl] Only Excellon objects can be used."
  3835. msgbox = QtWidgets.QMessageBox()
  3836. msgbox.setInformativeText(msg)
  3837. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3838. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3839. msgbox.exec_()
  3840. return
  3841. name = self.collection.get_active().options["name"]
  3842. filter = "Excellon File (*.drl);;Excellon File (*.txt);;All Files (*.*)"
  3843. try:
  3844. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon",
  3845. directory=self.get_last_save_folder(), filter=filter)
  3846. except TypeError:
  3847. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  3848. filename = str(filename)
  3849. if filename == "":
  3850. self.inform.emit("[warning_notcl]Export Excellon cancelled.")
  3851. return
  3852. else:
  3853. if altium_format == None:
  3854. self.export_excellon(name, filename)
  3855. self.file_saved.emit("Excellon", filename)
  3856. else:
  3857. self.export_excellon(name, filename, altium_format=True)
  3858. self.file_saved.emit("Excellon", filename)
  3859. def on_file_exportdxf(self):
  3860. """
  3861. Callback for menu item File->Export DXF.
  3862. :return: None
  3863. """
  3864. self.report_usage("on_file_exportdxf")
  3865. App.log.debug("on_file_exportdxf()")
  3866. obj = self.collection.get_active()
  3867. if obj is None:
  3868. self.inform.emit("W[warning_notcl] No object selected.")
  3869. msg = "Please Select a Geometry object to export"
  3870. msgbox = QtWidgets.QMessageBox()
  3871. msgbox.setInformativeText(msg)
  3872. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3873. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3874. msgbox.exec_()
  3875. return
  3876. # Check for more compatible types and add as required
  3877. if not isinstance(obj, FlatCAMGeometry):
  3878. msg = "[error_notcl] Only Geometry objects can be used."
  3879. msgbox = QtWidgets.QMessageBox()
  3880. msgbox.setInformativeText(msg)
  3881. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3882. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3883. msgbox.exec_()
  3884. return
  3885. name = self.collection.get_active().options["name"]
  3886. filter = "DXF File (*.DXF);;All Files (*.*)"
  3887. try:
  3888. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF",
  3889. directory=self.get_last_save_folder(), filter=filter)
  3890. except TypeError:
  3891. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  3892. filename = str(filename)
  3893. if filename == "":
  3894. self.inform.emit("[warning_notcl]Export DXF cancelled.")
  3895. return
  3896. else:
  3897. self.export_dxf(name, filename)
  3898. self.file_saved.emit("DXF", filename)
  3899. def on_file_importsvg(self, type_of_obj):
  3900. """
  3901. Callback for menu item File->Import SVG.
  3902. :param type_of_obj: to import the SVG as Geometry or as Gerber
  3903. :type type_of_obj: str
  3904. :return: None
  3905. """
  3906. self.report_usage("on_file_importsvg")
  3907. App.log.debug("on_file_importsvg()")
  3908. filter = "SVG File (*.svg);;All Files (*.*)"
  3909. try:
  3910. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG",
  3911. directory=self.get_last_folder(), filter=filter)
  3912. except TypeError:
  3913. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG", filter=filter)
  3914. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3915. type_of_obj = "geometry"
  3916. filenames = [str(filename) for filename in filenames]
  3917. if len(filenames) == 0:
  3918. self.inform.emit("[warning_notcl]Open SVG cancelled.")
  3919. else:
  3920. for filename in filenames:
  3921. if filename != '':
  3922. self.worker_task.emit({'fcn': self.import_svg,
  3923. 'params': [filename, type_of_obj]})
  3924. def on_file_importdxf(self, type_of_obj):
  3925. """
  3926. Callback for menu item File->Import DXF.
  3927. :param type_of_obj: to import the DXF as Geometry or as Gerber
  3928. :type type_of_obj: str
  3929. :return: None
  3930. """
  3931. self.report_usage("on_file_importdxf")
  3932. App.log.debug("on_file_importdxf()")
  3933. filter = "DXF File (*.DXF);;All Files (*.*)"
  3934. try:
  3935. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF",
  3936. directory=self.get_last_folder(), filter=filter)
  3937. except TypeError:
  3938. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF", filter=filter)
  3939. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3940. type_of_obj = "geometry"
  3941. filenames = [str(filename) for filename in filenames]
  3942. if len(filenames) == 0:
  3943. self.inform.emit("[warning_notcl]Open DXF cancelled.")
  3944. else:
  3945. for filename in filenames:
  3946. if filename != '':
  3947. self.worker_task.emit({'fcn': self.import_dxf,
  3948. 'params': [filename, type_of_obj]})
  3949. def on_filerunscript(self):
  3950. """
  3951. File menu callback for loading and running a TCL script.
  3952. :return: None
  3953. """
  3954. self.report_usage("on_filerunscript")
  3955. App.log.debug("on_file_runscript()")
  3956. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  3957. try:
  3958. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  3959. directory=self.get_last_folder(), filter=_filter_)
  3960. except TypeError:
  3961. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  3962. # The Qt methods above will return a QString which can cause problems later.
  3963. # So far json.dump() will fail to serialize it.
  3964. # TODO: Improve the serialization methods and remove this fix.
  3965. filename = str(filename)
  3966. if filename == "":
  3967. self.inform.emit("[warning_notcl]Open TCL script cancelled.")
  3968. else:
  3969. try:
  3970. with open(filename, "r") as tcl_script:
  3971. cmd_line_shellfile_content = tcl_script.read()
  3972. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  3973. except Exception as ext:
  3974. print("ERROR: ", ext)
  3975. sys.exit(2)
  3976. def on_file_saveproject(self):
  3977. """
  3978. Callback for menu item File->Save Project. Saves the project to
  3979. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  3980. if set to None. The project is saved by calling ``self.save_project()``.
  3981. :return: None
  3982. """
  3983. self.report_usage("on_file_saveproject")
  3984. if self.project_filename is None:
  3985. self.on_file_saveprojectas()
  3986. else:
  3987. self.worker_task.emit({'fcn': self.save_project,
  3988. 'params': [self.project_filename]})
  3989. # self.save_project(self.project_filename)
  3990. self.file_opened.emit("project", self.project_filename)
  3991. self.file_saved.emit("project", self.project_filename)
  3992. def on_file_saveprojectas(self, make_copy=False, thread=True):
  3993. """
  3994. Callback for menu item File->Save Project As... Opens a file
  3995. chooser and saves the project to the given file via
  3996. ``self.save_project()``.
  3997. :return: None
  3998. """
  3999. self.report_usage("on_file_saveprojectas")
  4000. filter = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  4001. try:
  4002. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...",
  4003. directory=self.get_last_save_folder(), filter=filter)
  4004. except TypeError:
  4005. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter)
  4006. filename = str(filename)
  4007. if filename == '':
  4008. self.inform.emit("[warning_notcl]Save Project cancelled.")
  4009. return
  4010. try:
  4011. f = open(filename, 'r')
  4012. f.close()
  4013. exists = True
  4014. except IOError:
  4015. exists = False
  4016. msg = "File exists. Overwrite?"
  4017. if exists:
  4018. msgbox = QtWidgets.QMessageBox()
  4019. msgbox.setInformativeText(msg)
  4020. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  4021. msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  4022. result = msgbox.exec_()
  4023. if result ==QtWidgets.QMessageBox.Cancel:
  4024. return
  4025. if thread is True:
  4026. self.worker_task.emit({'fcn': self.save_project,
  4027. 'params': [filename]})
  4028. else:
  4029. self.save_project(filename)
  4030. # self.save_project(filename)
  4031. self.file_opened.emit("project", filename)
  4032. self.file_saved.emit("project", filename)
  4033. if not make_copy:
  4034. self.project_filename = filename
  4035. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4036. """
  4037. Exports a Geometry Object to an SVG file.
  4038. :param filename: Path to the SVG file to save to.
  4039. :return:
  4040. """
  4041. if filename is None:
  4042. filename = self.defaults["global_last_save_folder"]
  4043. self.log.debug("export_svg()")
  4044. try:
  4045. obj = self.collection.get_by_name(str(obj_name))
  4046. except:
  4047. # TODO: The return behavior has not been established... should raise exception?
  4048. return "Could not retrieve object: %s" % obj_name
  4049. with self.proc_container.new("Exporting SVG") as proc:
  4050. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4051. # Determine bounding area for svg export
  4052. bounds = obj.bounds()
  4053. size = obj.size()
  4054. # Convert everything to strings for use in the xml doc
  4055. svgwidth = str(size[0])
  4056. svgheight = str(size[1])
  4057. minx = str(bounds[0])
  4058. miny = str(bounds[1] - size[1])
  4059. uom = obj.units.lower()
  4060. # Add a SVG Header and footer to the svg output from shapely
  4061. # The transform flips the Y Axis so that everything renders
  4062. # properly within svg apps such as inkscape
  4063. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4064. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4065. svg_header += 'width="' + svgwidth + uom + '" '
  4066. svg_header += 'height="' + svgheight + uom + '" '
  4067. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4068. svg_header += '<g transform="scale(1,-1)">'
  4069. svg_footer = '</g> </svg>'
  4070. svg_elem = svg_header + exported_svg + svg_footer
  4071. # Parse the xml through a xml parser just to add line feeds
  4072. # and to make it look more pretty for the output
  4073. svgcode = parse_xml_string(svg_elem)
  4074. with open(filename, 'w') as fp:
  4075. fp.write(svgcode.toprettyxml())
  4076. self.file_saved.emit("SVG", filename)
  4077. self.inform.emit("[success] SVG file exported to " + filename)
  4078. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4079. """
  4080. Exports a Geometry Object to an SVG file in negative.
  4081. :param filename: Path to the SVG file to save to.
  4082. :param: use_thread: If True use threads
  4083. :type: Bool
  4084. :return:
  4085. """
  4086. if filename is None:
  4087. filename = self.defaults["global_last_save_folder"]
  4088. self.log.debug("export_svg() negative")
  4089. try:
  4090. obj = self.collection.get_by_name(str(obj_name))
  4091. except:
  4092. # TODO: The return behavior has not been established... should raise exception?
  4093. return "Could not retrieve object: %s" % obj_name
  4094. try:
  4095. box = self.collection.get_by_name(str(box_name))
  4096. except:
  4097. # TODO: The return behavior has not been established... should raise exception?
  4098. return "Could not retrieve object: %s" % box_name
  4099. if box is None:
  4100. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  4101. box = obj
  4102. def make_negative_film():
  4103. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4104. self.progress.emit(40)
  4105. # Determine bounding area for svg export
  4106. bounds = box.bounds()
  4107. size = box.size()
  4108. uom = obj.units.lower()
  4109. # Convert everything to strings for use in the xml doc
  4110. svgwidth = str(size[0] + (2 * boundary))
  4111. svgheight = str(size[1] + (2 * boundary))
  4112. minx = str(bounds[0] - boundary)
  4113. miny = str(bounds[1] + boundary + size[1])
  4114. miny_rect = str(bounds[1] - boundary)
  4115. # Add a SVG Header and footer to the svg output from shapely
  4116. # The transform flips the Y Axis so that everything renders
  4117. # properly within svg apps such as inkscape
  4118. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4119. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4120. svg_header += 'width="' + svgwidth + uom + '" '
  4121. svg_header += 'height="' + svgheight + uom + '" '
  4122. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4123. svg_header += '>'
  4124. svg_header += '<g transform="scale(1,-1)">'
  4125. svg_footer = '</g> </svg>'
  4126. self.progress.emit(60)
  4127. # Change the attributes of the exported SVG
  4128. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4129. # We set opacity to maximum
  4130. # We set the color to WHITE
  4131. root = ET.fromstring(exported_svg)
  4132. for child in root:
  4133. child.set('fill', '#FFFFFF')
  4134. child.set('opacity', '1.0')
  4135. child.set('stroke', '#FFFFFF')
  4136. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4137. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4138. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4139. first_svg_elem_tag = 'rect'
  4140. first_svg_elem_attribs = {
  4141. 'x': minx,
  4142. 'y': miny_rect,
  4143. 'width': svgwidth,
  4144. 'height': svgheight,
  4145. 'id': 'neg_rect',
  4146. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4147. }
  4148. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4149. exported_svg = ET.tostring(root)
  4150. svg_elem = svg_header + str(exported_svg) + svg_footer
  4151. self.progress.emit(80)
  4152. # Parse the xml through a xml parser just to add line feeds
  4153. # and to make it look more pretty for the output
  4154. doc = parse_xml_string(svg_elem)
  4155. with open(filename, 'w') as fp:
  4156. fp.write(doc.toprettyxml())
  4157. self.progress.emit(100)
  4158. self.file_saved.emit("SVG", filename)
  4159. self.inform.emit("[success] SVG file exported to " + filename)
  4160. if use_thread is True:
  4161. proc = self.proc_container.new("Generating Film ... Please wait.")
  4162. def job_thread_film(app_obj):
  4163. try:
  4164. make_negative_film()
  4165. except Exception as e:
  4166. proc.done()
  4167. return
  4168. proc.done()
  4169. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4170. else:
  4171. make_negative_film()
  4172. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4173. """
  4174. Exports a Geometry Object to an SVG file in negative.
  4175. :param filename: Path to the SVG file to save to.
  4176. :param: use_thread: If True use threads
  4177. :type: Bool
  4178. :return:
  4179. """
  4180. if filename is None:
  4181. filename = self.defaults["global_last_save_folder"]
  4182. self.log.debug("export_svg() black")
  4183. try:
  4184. obj = self.collection.get_by_name(str(obj_name))
  4185. except:
  4186. # TODO: The return behavior has not been established... should raise exception?
  4187. return "Could not retrieve object: %s" % obj_name
  4188. try:
  4189. box = self.collection.get_by_name(str(box_name))
  4190. except:
  4191. # TODO: The return behavior has not been established... should raise exception?
  4192. return "Could not retrieve object: %s" % box_name
  4193. if box is None:
  4194. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  4195. box = obj
  4196. def make_black_film():
  4197. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4198. self.progress.emit(40)
  4199. # Change the attributes of the exported SVG
  4200. # We don't need stroke-width
  4201. # We set opacity to maximum
  4202. # We set the colour to WHITE
  4203. root = ET.fromstring(exported_svg)
  4204. for child in root:
  4205. child.set('fill', '#000000')
  4206. child.set('opacity', '1.0')
  4207. child.set('stroke', '#000000')
  4208. exported_svg = ET.tostring(root)
  4209. # Determine bounding area for svg export
  4210. bounds = box.bounds()
  4211. size = box.size()
  4212. # This contain the measure units
  4213. uom = obj.units.lower()
  4214. # Define a boundary around SVG of about 1.0mm (~39mils)
  4215. if uom in "mm":
  4216. boundary = 1.0
  4217. else:
  4218. boundary = 0.0393701
  4219. self.progress.emit(80)
  4220. # Convert everything to strings for use in the xml doc
  4221. svgwidth = str(size[0] + (2 * boundary))
  4222. svgheight = str(size[1] + (2 * boundary))
  4223. minx = str(bounds[0] - boundary)
  4224. miny = str(bounds[1] + boundary + size[1])
  4225. self.log.debug(minx)
  4226. self.log.debug(miny)
  4227. # Add a SVG Header and footer to the svg output from shapely
  4228. # The transform flips the Y Axis so that everything renders
  4229. # properly within svg apps such as inkscape
  4230. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4231. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4232. svg_header += 'width="' + svgwidth + uom + '" '
  4233. svg_header += 'height="' + svgheight + uom + '" '
  4234. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4235. svg_header += '>'
  4236. svg_header += '<g transform="scale(1,-1)">'
  4237. svg_footer = '</g> </svg>'
  4238. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  4239. self.progress.emit(90)
  4240. # Parse the xml through a xml parser just to add line feeds
  4241. # and to make it look more pretty for the output
  4242. doc = parse_xml_string(svg_elem)
  4243. with open(filename, 'w') as fp:
  4244. fp.write(doc.toprettyxml())
  4245. self.progress.emit(100)
  4246. self.file_saved.emit("SVG", filename)
  4247. self.inform.emit("[success] SVG file exported to " + filename)
  4248. if use_thread is True:
  4249. proc = self.proc_container.new("Generating Film ... Please wait.")
  4250. def job_thread_film(app_obj):
  4251. try:
  4252. make_black_film()
  4253. except Exception as e:
  4254. proc.done()
  4255. return
  4256. proc.done()
  4257. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4258. else:
  4259. make_black_film()
  4260. def export_excellon(self, obj_name, filename, altium_format=None, use_thread=True):
  4261. """
  4262. Exports a Geometry Object to an Excellon file.
  4263. :param filename: Path to the Excellon file to save to.
  4264. :return:
  4265. """
  4266. if filename is None:
  4267. filename = self.defaults["global_last_save_folder"]
  4268. self.log.debug("export_excellon()")
  4269. format_exc = ';FILE_FORMAT=2:4\n'
  4270. units = ''
  4271. try:
  4272. obj = self.collection.get_by_name(str(obj_name))
  4273. except:
  4274. # TODO: The return behavior has not been established... should raise exception?
  4275. return "Could not retrieve object: %s" % obj_name
  4276. # updated units
  4277. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4278. if units == 'IN' or units == 'INCH':
  4279. units = 'INCH'
  4280. elif units == 'MM' or units == 'METRIC':
  4281. units ='METRIC'
  4282. def make_excellon():
  4283. try:
  4284. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4285. header = 'M48\n'
  4286. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4287. (str(self.app.version), str(self.app.version_date))
  4288. header += ';Filename: %s' % str(obj_name) + '\n'
  4289. header += ';Created on : %s' % time_str + '\n'
  4290. if altium_format == None:
  4291. has_slots, excellon_code = obj.export_excellon()
  4292. header += units + '\n'
  4293. for tool in obj.tools:
  4294. if units == 'METRIC':
  4295. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.2f' % float(obj.tools[tool]['C']) + '\n'
  4296. else:
  4297. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4298. else:
  4299. has_slots, excellon_code = obj.export_excellon_altium()
  4300. header += 'INCH,LZ\n'
  4301. header += format_exc
  4302. for tool in obj.tools:
  4303. if units == 'METRIC':
  4304. header += 'T' + str(tool) + 'F00S00' + 'C' + \
  4305. '%.4f' % (float(obj.tools[tool]['C']) / 25.4) + '\n'
  4306. else:
  4307. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4308. header += '%\n'
  4309. footer = 'M30\n'
  4310. exported_excellon = header
  4311. exported_excellon += excellon_code
  4312. exported_excellon += footer
  4313. with open(filename, 'w') as fp:
  4314. fp.write(exported_excellon)
  4315. self.file_saved.emit("Excellon", filename)
  4316. self.inform.emit("[success] Excellon file exported to " + filename)
  4317. except:
  4318. return 'fail'
  4319. if use_thread is True:
  4320. with self.proc_container.new("Exporting Excellon") as proc:
  4321. def job_thread_exc(app_obj):
  4322. ret = make_excellon()
  4323. if ret == 'fail':
  4324. self.inform.emit('[error_notcl] Could not export Excellon file.')
  4325. return
  4326. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4327. else:
  4328. ret = make_excellon()
  4329. if ret == 'fail':
  4330. self.inform.emit('[error_notcl] Could not export Excellon file.')
  4331. return
  4332. def export_dxf(self, obj_name, filename, use_thread=True):
  4333. """
  4334. Exports a Geometry Object to an DXF file.
  4335. :param filename: Path to the DXF file to save to.
  4336. :return:
  4337. """
  4338. if filename is None:
  4339. filename = self.defaults["global_last_save_folder"]
  4340. self.log.debug("export_dxf()")
  4341. format_exc = ''
  4342. units = ''
  4343. try:
  4344. obj = self.collection.get_by_name(str(obj_name))
  4345. except:
  4346. # TODO: The return behavior has not been established... should raise exception?
  4347. return "Could not retrieve object: %s" % obj_name
  4348. # updated units
  4349. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4350. if units == 'IN' or units == 'INCH':
  4351. units = 'INCH'
  4352. elif units == 'MM' or units == 'METIRC':
  4353. units ='METRIC'
  4354. def make_dxf():
  4355. try:
  4356. dxf_code = obj.export_dxf()
  4357. dxf_code.saveas(filename)
  4358. self.file_saved.emit("DXF", filename)
  4359. self.inform.emit("[success] DXF file exported to " + filename)
  4360. except:
  4361. return 'fail'
  4362. if use_thread is True:
  4363. with self.proc_container.new("Exporting DXF") as proc:
  4364. def job_thread_exc(app_obj):
  4365. ret = make_dxf()
  4366. if ret == 'fail':
  4367. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4368. return
  4369. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4370. else:
  4371. ret = make_dxf()
  4372. if ret == 'fail':
  4373. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4374. return
  4375. def import_svg(self, filename, geo_type='geometry', outname=None):
  4376. """
  4377. Adds a new Geometry Object to the projects and populates
  4378. it with shapes extracted from the SVG file.
  4379. :param filename: Path to the SVG file.
  4380. :param outname:
  4381. :return:
  4382. """
  4383. obj_type = ""
  4384. if geo_type is None or geo_type == "geometry":
  4385. obj_type = "geometry"
  4386. elif geo_type == "gerber":
  4387. obj_type = geo_type
  4388. else:
  4389. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4390. "Only Geometry and Gerber are supported")
  4391. return
  4392. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4393. def obj_init(geo_obj, app_obj):
  4394. geo_obj.import_svg(filename, obj_type, units=units)
  4395. geo_obj.multigeo = False
  4396. with self.proc_container.new("Importing SVG") as proc:
  4397. # Object name
  4398. name = outname or filename.split('/')[-1].split('\\')[-1]
  4399. self.new_object(obj_type, name, obj_init, autoselected=False)
  4400. self.progress.emit(20)
  4401. # Register recent file
  4402. self.file_opened.emit("svg", filename)
  4403. # GUI feedback
  4404. self.inform.emit("[success] Opened: " + filename)
  4405. self.progress.emit(100)
  4406. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4407. """
  4408. Adds a new Geometry Object to the projects and populates
  4409. it with shapes extracted from the DXF file.
  4410. :param filename: Path to the DXF file.
  4411. :param outname:
  4412. :type putname: str
  4413. :return:
  4414. """
  4415. obj_type = ""
  4416. if geo_type is None or geo_type == "geometry":
  4417. obj_type = "geometry"
  4418. elif geo_type == "gerber":
  4419. obj_type = geo_type
  4420. else:
  4421. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4422. "Only Geometry and Gerber are supported")
  4423. return
  4424. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4425. def obj_init(geo_obj, app_obj):
  4426. geo_obj.import_dxf(filename, obj_type, units=units)
  4427. geo_obj.multigeo = False
  4428. with self.proc_container.new("Importing DXF") as proc:
  4429. # Object name
  4430. name = outname or filename.split('/')[-1].split('\\')[-1]
  4431. self.new_object(obj_type, name, obj_init, autoselected=False)
  4432. self.progress.emit(20)
  4433. # Register recent file
  4434. self.file_opened.emit("dxf", filename)
  4435. # GUI feedback
  4436. self.inform.emit("[success] Opened: " + filename)
  4437. self.progress.emit(100)
  4438. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4439. """
  4440. Adds a new Geometry Object to the projects and populates
  4441. it with shapes extracted from the SVG file.
  4442. :param filename: Path to the SVG file.
  4443. :param outname:
  4444. :return:
  4445. """
  4446. obj_type = ""
  4447. if type is None or type == "geometry":
  4448. obj_type = "geometry"
  4449. elif type == "gerber":
  4450. obj_type = type
  4451. else:
  4452. self.inform.emit("[error_notcl] Not supported type was picked as parameter. "
  4453. "Only Geometry and Gerber are supported")
  4454. return
  4455. def obj_init(geo_obj, app_obj):
  4456. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4457. geo_obj.multigeo = False
  4458. with self.proc_container.new("Importing Image") as proc:
  4459. # Object name
  4460. name = outname or filename.split('/')[-1].split('\\')[-1]
  4461. units = self.general_options_form.general_app_group.units_radio.get_value()
  4462. self.new_object(obj_type, name, obj_init)
  4463. self.progress.emit(20)
  4464. # Register recent file
  4465. self.file_opened.emit("image", filename)
  4466. # GUI feedback
  4467. self.inform.emit("[success] Opened: " + filename)
  4468. self.progress.emit(100)
  4469. def open_gerber(self, filename, follow=False, outname=None):
  4470. """
  4471. Opens a Gerber file, parses it and creates a new object for
  4472. it in the program. Thread-safe.
  4473. :param outname: Name of the resulting object. None causes the
  4474. name to be that of the file.
  4475. :param filename: Gerber file filename
  4476. :type filename: str
  4477. :param follow: If true, the parser will not create polygons, just lines
  4478. following the gerber path.
  4479. :type follow: bool
  4480. :return: None
  4481. """
  4482. # How the object should be initialized
  4483. def obj_init(gerber_obj, app_obj):
  4484. assert isinstance(gerber_obj, FlatCAMGerber), \
  4485. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4486. # Opening the file happens here
  4487. self.progress.emit(30)
  4488. try:
  4489. gerber_obj.parse_file(filename, follow=follow)
  4490. except IOError:
  4491. app_obj.inform.emit("[error_notcl] Failed to open file: " + filename)
  4492. app_obj.progress.emit(0)
  4493. self.inform.emit('[error_notcl] Failed to open file: ' + filename)
  4494. return "fail"
  4495. except ParseError as err:
  4496. app_obj.inform.emit("[error_notcl] Failed to parse file: " + filename + ". " + str(err))
  4497. app_obj.progress.emit(0)
  4498. self.log.error(str(err))
  4499. return "fail"
  4500. except:
  4501. msg = "[error] An internal error has ocurred. See shell.\n"
  4502. msg += traceback.format_exc()
  4503. app_obj.inform.emit(msg)
  4504. return "fail"
  4505. if gerber_obj.is_empty():
  4506. # app_obj.inform.emit("[error] No geometry found in file: " + filename)
  4507. # self.collection.set_active(gerber_obj.options["name"])
  4508. # self.collection.delete_active()
  4509. self.inform.emit("[error_notcl] Object is not Gerber file or empty. Aborting object creation.")
  4510. return "fail"
  4511. # Further parsing
  4512. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4513. if follow is False:
  4514. App.log.debug("open_gerber()")
  4515. else:
  4516. App.log.debug("open_gerber() with 'follow' attribute")
  4517. with self.proc_container.new("Opening Gerber") as proc:
  4518. self.progress.emit(10)
  4519. # Object name
  4520. name = outname or filename.split('/')[-1].split('\\')[-1]
  4521. ### Object creation ###
  4522. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4523. if ret == 'fail':
  4524. self.inform.emit('[error_notcl] Open Gerber failed. Probable not a Gerber file.')
  4525. return
  4526. # Register recent file
  4527. self.file_opened.emit("gerber", filename)
  4528. self.progress.emit(100)
  4529. # GUI feedback
  4530. self.inform.emit("[success] Opened: " + filename)
  4531. def open_excellon(self, filename, outname=None):
  4532. """
  4533. Opens an Excellon file, parses it and creates a new object for
  4534. it in the program. Thread-safe.
  4535. :param outname: Name of the resulting object. None causes the
  4536. name to be that of the file.
  4537. :param filename: Excellon file filename
  4538. :type filename: str
  4539. :return: None
  4540. """
  4541. App.log.debug("open_excellon()")
  4542. #self.progress.emit(10)
  4543. # How the object should be initialized
  4544. def obj_init(excellon_obj, app_obj):
  4545. # self.progress.emit(20)
  4546. try:
  4547. ret = excellon_obj.parse_file(filename)
  4548. if ret == "fail":
  4549. log.debug("Excellon parsing failed.")
  4550. self.inform.emit("[error_notcl] This is not Excellon file.")
  4551. return "fail"
  4552. except IOError:
  4553. app_obj.inform.emit("[error_notcl] Cannot open file: " + filename)
  4554. log.debug("Could not open Excellon object.")
  4555. self.progress.emit(0) # TODO: self and app_bjj mixed
  4556. return "fail"
  4557. except:
  4558. msg = "[error_notcl] An internal error has occurred. See shell.\n"
  4559. msg += traceback.format_exc()
  4560. app_obj.inform.emit(msg)
  4561. return "fail"
  4562. ret = excellon_obj.create_geometry()
  4563. if ret == 'fail':
  4564. log.debug("Could not create geometry for Excellon object.")
  4565. return "fail"
  4566. if excellon_obj.is_empty():
  4567. app_obj.inform.emit("[error_notcl] No geometry found in file: " + filename)
  4568. return "fail"
  4569. with self.proc_container.new("Opening Excellon."):
  4570. # Object name
  4571. name = outname or filename.split('/')[-1].split('\\')[-1]
  4572. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  4573. if ret == 'fail':
  4574. self.inform.emit('[error_notcl] Open Excellon file failed. Probable not an Excellon file.')
  4575. return
  4576. # Register recent file
  4577. self.file_opened.emit("excellon", filename)
  4578. # GUI feedback
  4579. self.inform.emit("[success] Opened: " + filename)
  4580. # self.progress.emit(100)
  4581. def open_gcode(self, filename, outname=None):
  4582. """
  4583. Opens a G-gcode file, parses it and creates a new object for
  4584. it in the program. Thread-safe.
  4585. :param outname: Name of the resulting object. None causes the
  4586. name to be that of the file.
  4587. :param filename: G-code file filename
  4588. :type filename: str
  4589. :return: None
  4590. """
  4591. App.log.debug("open_gcode()")
  4592. # How the object should be initialized
  4593. def obj_init(job_obj, app_obj_):
  4594. """
  4595. :type app_obj_: App
  4596. """
  4597. assert isinstance(app_obj_, App), \
  4598. "Initializer expected App, got %s" % type(app_obj_)
  4599. self.progress.emit(10)
  4600. try:
  4601. f = open(filename)
  4602. gcode = f.read()
  4603. f.close()
  4604. except IOError:
  4605. app_obj_.inform.emit("[error_notcl] Failed to open " + filename)
  4606. self.progress.emit(0)
  4607. return "fail"
  4608. job_obj.gcode = gcode
  4609. self.progress.emit(20)
  4610. ret = job_obj.gcode_parse()
  4611. if ret == "fail":
  4612. self.inform.emit("[error_notcl] This is not GCODE")
  4613. return "fail"
  4614. self.progress.emit(60)
  4615. job_obj.create_geometry()
  4616. with self.proc_container.new("Opening G-Code."):
  4617. # Object name
  4618. name = outname or filename.split('/')[-1].split('\\')[-1]
  4619. # New object creation and file processing
  4620. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  4621. if ret == 'fail':
  4622. self.inform.emit("[error_notcl] Failed to create CNCJob Object. Probable not a GCode file.\n "
  4623. "Attempting to create a FlatCAM CNCJob Object from "
  4624. "G-Code file failed during processing")
  4625. return "fail"
  4626. # Register recent file
  4627. self.file_opened.emit("cncjob", filename)
  4628. # GUI feedback
  4629. self.inform.emit("[success] Opened: " + filename)
  4630. self.progress.emit(100)
  4631. def open_project(self, filename, run_from_arg=None):
  4632. """
  4633. Loads a project from the specified file.
  4634. 1) Loads and parses file
  4635. 2) Registers the file as recently opened.
  4636. 3) Calls on_file_new()
  4637. 4) Updates options
  4638. 5) Calls new_object() with the object's from_dict() as init method.
  4639. 6) Calls plot_all()
  4640. :param filename: Name of the file from which to load.
  4641. :type filename: str
  4642. :return: None
  4643. """
  4644. App.log.debug("Opening project: " + filename)
  4645. # Open and parse
  4646. try:
  4647. f = open(filename, 'r')
  4648. except IOError:
  4649. App.log.error("Failed to open project file: %s" % filename)
  4650. self.inform.emit("[error_notcl] Failed to open project file: %s" % filename)
  4651. return
  4652. try:
  4653. d = json.load(f, object_hook=dict2obj)
  4654. except:
  4655. App.log.error("Failed to parse project file: %s" % filename)
  4656. self.inform.emit("[error_notcl] Failed to parse project file: %s" % filename)
  4657. f.close()
  4658. return
  4659. self.file_opened.emit("project", filename)
  4660. # Clear the current project
  4661. ## NOT THREAD SAFE ##
  4662. if run_from_arg is True:
  4663. pass
  4664. else:
  4665. self.on_file_new()
  4666. #Project options
  4667. self.options.update(d['options'])
  4668. self.project_filename = filename
  4669. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4670. self.set_screen_units(self.options["units"])
  4671. # Re create objects
  4672. App.log.debug("Re-creating objects...")
  4673. for obj in d['objs']:
  4674. def obj_init(obj_inst, app_inst):
  4675. obj_inst.from_dict(obj)
  4676. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  4677. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  4678. # self.plot_all()
  4679. self.inform.emit("[success] Project loaded from: " + filename)
  4680. App.log.debug("Project loaded")
  4681. def propagate_defaults(self, silent=False):
  4682. """
  4683. This method is used to set default values in classes. It's
  4684. an alternative to project options but allows the use
  4685. of values invisible to the user.
  4686. :return: None
  4687. """
  4688. if silent is False:
  4689. self.log.debug("propagate_defaults()")
  4690. # Which objects to update the given parameters.
  4691. routes = {
  4692. "global_zdownrate": CNCjob,
  4693. "excellon_zeros": Excellon,
  4694. "excellon_format_upper_in": Excellon,
  4695. "excellon_format_lower_in": Excellon,
  4696. "excellon_format_upper_mm": Excellon,
  4697. "excellon_format_lower_mm": Excellon,
  4698. "excellon_units": Excellon,
  4699. "gerber_use_buffer_for_union": Gerber,
  4700. "geometry_multidepth": Geometry
  4701. }
  4702. for param in routes:
  4703. if param in routes[param].defaults:
  4704. try:
  4705. routes[param].defaults[param] = self.defaults[param]
  4706. if silent is False:
  4707. self.log.debug(" " + param + " OK")
  4708. except KeyError:
  4709. if silent is False:
  4710. self.log.debug(" ERROR: " + param + " not in defaults.")
  4711. else:
  4712. # Try extracting the name:
  4713. # classname_param here is param in the object
  4714. if param.find(routes[param].__name__.lower() + "_") == 0:
  4715. p = param[len(routes[param].__name__) + 1:]
  4716. if p in routes[param].defaults:
  4717. routes[param].defaults[p] = self.defaults[param]
  4718. if silent is False:
  4719. self.log.debug(" " + param + " OK!")
  4720. def restore_main_win_geom(self):
  4721. try:
  4722. self.ui.setGeometry(self.defaults["global_def_win_x"],
  4723. self.defaults["global_def_win_y"],
  4724. self.defaults["global_def_win_w"],
  4725. self.defaults["global_def_win_h"])
  4726. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  4727. except KeyError:
  4728. pass
  4729. def plot_all(self):
  4730. """
  4731. Re-generates all plots from all objects.
  4732. :return: None
  4733. """
  4734. self.log.debug("Plot_all()")
  4735. for obj in self.collection.get_list():
  4736. def worker_task(obj):
  4737. with self.proc_container.new("Plotting"):
  4738. obj.plot()
  4739. self.object_plotted.emit(obj)
  4740. # Send to worker
  4741. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  4742. # self.progress.emit(10)
  4743. #
  4744. # def worker_task(app_obj):
  4745. # print "worker task"
  4746. # percentage = 0.1
  4747. # try:
  4748. # delta = 0.9 / len(self.collection.get_list())
  4749. # except ZeroDivisionError:
  4750. # self.progress.emit(0)
  4751. # return
  4752. # for obj in self.collection.get_list():
  4753. # with self.proc_container.new("Plotting"):
  4754. # obj.plot()
  4755. # app_obj.object_plotted.emit(obj)
  4756. #
  4757. # percentage += delta
  4758. # self.progress.emit(int(percentage*100))
  4759. #
  4760. # self.progress.emit(0)
  4761. # self.plots_updated.emit()
  4762. #
  4763. # # Send to worker
  4764. # #self.worker.add_task(worker_task, [self])
  4765. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  4766. def register_folder(self, filename):
  4767. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  4768. def register_save_folder(self, filename):
  4769. self.defaults['global_last_save_folder'] = os.path.split(str(filename))[0]
  4770. def set_progress_bar(self, percentage, text=""):
  4771. self.ui.progress_bar.setValue(int(percentage))
  4772. def setup_shell(self):
  4773. """
  4774. Creates shell functions. Runs once at startup.
  4775. :return: None
  4776. """
  4777. self.log.debug("setup_shell()")
  4778. def shelp(p=None):
  4779. if not p:
  4780. return "Available commands:\n" + \
  4781. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  4782. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  4783. if p not in commands:
  4784. return "Unknown command: %s" % p
  4785. return commands[p]["help"]
  4786. # --- Migrated to new architecture ---
  4787. # def options(name):
  4788. # ops = self.collection.get_by_name(str(name)).options
  4789. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  4790. def h(*args):
  4791. """
  4792. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  4793. and standalone parameters into list.
  4794. """
  4795. kwa = {}
  4796. a = []
  4797. n = len(args)
  4798. name = None
  4799. for i in range(n):
  4800. match = re.search(r'^-([a-zA-Z].*)', args[i])
  4801. if match:
  4802. assert name is None
  4803. name = match.group(1)
  4804. continue
  4805. if name is None:
  4806. a.append(args[i])
  4807. else:
  4808. kwa[name] = args[i]
  4809. name = None
  4810. return a, kwa
  4811. @contextmanager
  4812. def wait_signal(signal, timeout=10000):
  4813. """
  4814. Block loop until signal emitted, timeout (ms) elapses
  4815. or unhandled exception happens in a thread.
  4816. :param signal: Signal to wait for.
  4817. """
  4818. loop = QtCore.QEventLoop()
  4819. # Normal termination
  4820. signal.connect(loop.quit)
  4821. # Termination by exception in thread
  4822. self.thread_exception.connect(loop.quit)
  4823. status = {'timed_out': False}
  4824. def report_quit():
  4825. status['timed_out'] = True
  4826. loop.quit()
  4827. yield
  4828. # Temporarily change how exceptions are managed.
  4829. oeh = sys.excepthook
  4830. ex = []
  4831. def except_hook(type_, value, traceback_):
  4832. ex.append(value)
  4833. oeh(type_, value, traceback_)
  4834. sys.excepthook = except_hook
  4835. # Terminate on timeout
  4836. if timeout is not None:
  4837. QtCore.QTimer.singleShot(timeout, report_quit)
  4838. #### Block ####
  4839. loop.exec_()
  4840. # Restore exception management
  4841. sys.excepthook = oeh
  4842. if ex:
  4843. self.raiseTclError(str(ex[0]))
  4844. if status['timed_out']:
  4845. raise Exception('Timed out!')
  4846. def make_docs():
  4847. output = ''
  4848. import collections
  4849. od = collections.OrderedDict(sorted(commands.items()))
  4850. for cmd_, val in od.items():
  4851. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  4852. t = val['help']
  4853. usage_i = t.find('>')
  4854. if usage_i < 0:
  4855. expl = t
  4856. output += expl + '\n\n'
  4857. continue
  4858. expl = t[:usage_i - 1]
  4859. output += expl + '\n\n'
  4860. end_usage_i = t[usage_i:].find('\n')
  4861. if end_usage_i < 0:
  4862. end_usage_i = len(t[usage_i:])
  4863. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  4864. else:
  4865. extras = t[usage_i+end_usage_i+1:]
  4866. parts = [s.strip() for s in extras.split('\n')]
  4867. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  4868. for p in parts:
  4869. output += ' ' + p + '\n\n'
  4870. return output
  4871. '''
  4872. Howto implement TCL shell commands:
  4873. All parameters passed to command should be possible to set as None and test it afterwards.
  4874. This is because we need to see error caused in tcl,
  4875. if None value as default parameter is not allowed TCL will return empty error.
  4876. Use:
  4877. def mycommand(name=None,...):
  4878. Test it like this:
  4879. if name is None:
  4880. self.raise_tcl_error('Argument name is missing.')
  4881. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  4882. otherwise we will miss it and processing will silently continue.
  4883. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  4884. which is catched in exec_command and displayed in TCL shell console with red background.
  4885. Error in console is displayed with TCL trace.
  4886. This behavior works only within main thread,
  4887. errors with promissed tasks can be catched and detected only with log.
  4888. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  4889. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  4890. '''
  4891. commands = {
  4892. 'help': {
  4893. 'fcn': shelp,
  4894. 'help': "Shows list of commands."
  4895. },
  4896. }
  4897. # Import/overwrite tcl commands as objects of TclCommand descendants
  4898. # This modifies the variable 'commands'.
  4899. tclCommands.register_all_commands(self, commands)
  4900. # Add commands to the tcl interpreter
  4901. for cmd in commands:
  4902. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  4903. # Make the tcl puts function return instead of print to stdout
  4904. self.tcl.eval('''
  4905. rename puts original_puts
  4906. proc puts {args} {
  4907. if {[llength $args] == 1} {
  4908. return "[lindex $args 0]"
  4909. } else {
  4910. eval original_puts $args
  4911. }
  4912. }
  4913. ''')
  4914. def setup_recent_items(self):
  4915. # TODO: Move this to constructor
  4916. icons = {
  4917. "gerber": "share/flatcam_icon16.png",
  4918. "excellon": "share/drill16.png",
  4919. "cncjob": "share/cnc16.png",
  4920. "project": "share/project16.png",
  4921. "svg": "share/geometry16.png",
  4922. "dxf": "share/dxf16.png",
  4923. "image": "share/image16.png"
  4924. }
  4925. openers = {
  4926. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  4927. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  4928. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  4929. 'project': self.open_project,
  4930. 'svg': self.import_svg,
  4931. 'dxf': self.import_dxf,
  4932. 'image': self.import_image
  4933. }
  4934. # Open file
  4935. try:
  4936. f = open(self.data_path + '/recent.json')
  4937. except IOError:
  4938. App.log.error("Failed to load recent item list.")
  4939. self.inform.emit("[error_notcl] Failed to load recent item list.")
  4940. return
  4941. try:
  4942. self.recent = json.load(f)
  4943. except json.scanner.JSONDecodeError:
  4944. App.log.error("Failed to parse recent item list.")
  4945. self.inform.emit("[error_notcl] Failed to parse recent item list.")
  4946. f.close()
  4947. return
  4948. f.close()
  4949. # Closure needed to create callbacks in a loop.
  4950. # Otherwise late binding occurs.
  4951. def make_callback(func, fname):
  4952. def opener():
  4953. func(fname)
  4954. return opener
  4955. def reset_recent():
  4956. # Reset menu
  4957. self.ui.recent.clear()
  4958. self.recent = []
  4959. try:
  4960. f = open(self.data_path + '/recent.json', 'w')
  4961. except IOError:
  4962. App.log.error("Failed to open recent items file for writing.")
  4963. return
  4964. json.dump(self.recent, f)
  4965. # Reset menu
  4966. self.ui.recent.clear()
  4967. # Create menu items
  4968. for recent in self.recent:
  4969. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  4970. try:
  4971. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  4972. # Attach callback
  4973. o = make_callback(openers[recent["kind"]], recent['filename'])
  4974. action.triggered.connect(o)
  4975. self.ui.recent.addAction(action)
  4976. except KeyError:
  4977. App.log.error("Unsupported file type: %s" % recent["kind"])
  4978. # Last action in Recent Files menu is one that Clear the content
  4979. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  4980. clear_action.triggered.connect(reset_recent)
  4981. self.ui.recent.addSeparator()
  4982. self.ui.recent.addAction(clear_action)
  4983. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  4984. # self.ui.menufilerecent.set_submenu(recent_menu)
  4985. # recent_menu.show_all()
  4986. # self.ui.recent.show()
  4987. self.log.debug("Recent items list has been populated.")
  4988. def setup_component_editor(self):
  4989. label = QtWidgets.QLabel("Choose an item from Project")
  4990. label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  4991. self.ui.selected_scroll_area.setWidget(label)
  4992. def setup_obj_classes(self):
  4993. """
  4994. Sets up application specifics on the FlatCAMObj class.
  4995. :return: None
  4996. """
  4997. FlatCAMObj.app = self
  4998. ObjectCollection.app = self
  4999. FCProcess.app = self
  5000. FCProcessContainer.app = self
  5001. def version_check(self):
  5002. """
  5003. Checks for the latest version of the program. Alerts the
  5004. user if theirs is outdated. This method is meant to be run
  5005. in a separate thread.
  5006. :return: None
  5007. """
  5008. self.log.debug("version_check()")
  5009. if self.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  5010. full_url = App.version_url + \
  5011. "?s=" + str(self.defaults['global_serial']) + \
  5012. "&v=" + str(self.version) + \
  5013. "&os=" + str(self.os) + \
  5014. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  5015. else:
  5016. # no_stats dict; just so it won't break things on website
  5017. no_ststs_dict = {}
  5018. no_ststs_dict["global_ststs"] = {}
  5019. full_url = App.version_url + \
  5020. "?s=" + str(self.defaults['global_serial']) + \
  5021. "&v=" + str(self.version) + \
  5022. "&os=" + str(self.os) + \
  5023. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  5024. App.log.debug("Checking for updates @ %s" % full_url)
  5025. ### Get the data
  5026. try:
  5027. f = urllib.request.urlopen(full_url)
  5028. except:
  5029. # App.log.warning("Failed checking for latest version. Could not connect.")
  5030. self.log.warning("Failed checking for latest version. Could not connect.")
  5031. self.inform.emit("[warning_notcl] Failed checking for latest version. Could not connect.")
  5032. return
  5033. try:
  5034. data = json.load(f)
  5035. except Exception as e:
  5036. App.log.error("Could not parse information about latest version.")
  5037. self.inform.emit("[error_notcl] Could not parse information about latest version.")
  5038. App.log.debug("json.load(): %s" % str(e))
  5039. f.close()
  5040. return
  5041. f.close()
  5042. ### Latest version?
  5043. if self.version >= data["version"]:
  5044. App.log.debug("FlatCAM is up to date!")
  5045. self.inform.emit("[success] FlatCAM is up to date!")
  5046. return
  5047. App.log.debug("Newer version available.")
  5048. self.message.emit(
  5049. "Newer Version Available",
  5050. str("There is a newer version of FlatCAM " +
  5051. "available for download:<br><br>" +
  5052. "<B>" + data["name"] + "</b><br>" +
  5053. data["message"].replace("\n", "<br>")),
  5054. "info"
  5055. )
  5056. def on_zoom_fit(self, event):
  5057. """
  5058. Callback for zoom-out request. This can be either from the corresponding
  5059. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  5060. with axes limits from the geometry bounds of all objects.
  5061. :param event: Ignored.
  5062. :return: None
  5063. """
  5064. self.plotcanvas.fit_view()
  5065. def disable_all_plots(self):
  5066. self.disable_plots(self.collection.get_list())
  5067. self.inform.emit("[success]All plots disabled.")
  5068. def disable_other_plots(self):
  5069. self.disable_plots(self.collection.get_non_selected())
  5070. self.inform.emit("[success]All non selected plots disabled.")
  5071. def enable_all_plots(self):
  5072. self.enable_plots(self.collection.get_list())
  5073. self.inform.emit("[success]All plots enabled.")
  5074. # TODO: FIX THIS
  5075. '''
  5076. By default this is not threaded
  5077. If threaded the app give warnings like this:
  5078. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5079. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5080. '''
  5081. def enable_plots(self, objects, threaded=False):
  5082. if threaded is True:
  5083. def worker_task(app_obj):
  5084. percentage = 0.1
  5085. try:
  5086. delta = 0.9 / len(objects)
  5087. except ZeroDivisionError:
  5088. self.progress.emit(0)
  5089. return
  5090. for obj in objects:
  5091. obj.options['plot'] = True
  5092. percentage += delta
  5093. self.progress.emit(int(percentage*100))
  5094. self.progress.emit(0)
  5095. self.plots_updated.emit()
  5096. self.collection.update_view()
  5097. # Send to worker
  5098. # self.worker.add_task(worker_task, [self])
  5099. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5100. else:
  5101. for obj in objects:
  5102. obj.options['plot'] = True
  5103. self.progress.emit(0)
  5104. self.plots_updated.emit()
  5105. self.collection.update_view()
  5106. # TODO: FIX THIS
  5107. '''
  5108. By default this is not threaded
  5109. If threaded the app give warnings like this:
  5110. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5111. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5112. '''
  5113. def disable_plots(self, objects, threaded=False):
  5114. # TODO: This method is very similar to replot_all. Try to merge.
  5115. """
  5116. Disables plots
  5117. :param objects: list
  5118. Objects to be disabled
  5119. :return:
  5120. """
  5121. if threaded is True:
  5122. self.progress.emit(10)
  5123. def worker_task(app_obj):
  5124. percentage = 0.1
  5125. try:
  5126. delta = 0.9 / len(objects)
  5127. except ZeroDivisionError:
  5128. self.progress.emit(0)
  5129. return
  5130. for obj in objects:
  5131. obj.options['plot'] = False
  5132. percentage += delta
  5133. self.progress.emit(int(percentage*100))
  5134. self.progress.emit(0)
  5135. self.plots_updated.emit()
  5136. self.collection.update_view()
  5137. # Send to worker
  5138. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5139. else:
  5140. for obj in objects:
  5141. obj.options['plot'] = False
  5142. self.plots_updated.emit()
  5143. self.collection.update_view()
  5144. def clear_plots(self):
  5145. objects = self.collection.get_list()
  5146. for obj in objects:
  5147. obj.clear(obj == objects[-1])
  5148. # Clear pool to free memory
  5149. self.clear_pool()
  5150. def generate_cnc_job(self, objects):
  5151. for obj in objects:
  5152. obj.generatecncjob()
  5153. def save_project(self, filename):
  5154. """
  5155. Saves the current project to the specified file.
  5156. :param filename: Name of the file in which to save.
  5157. :type filename: str
  5158. :return: None
  5159. """
  5160. self.log.debug("save_project()")
  5161. with self.proc_container.new("Saving FlatCAM Project") as proc:
  5162. ## Capture the latest changes
  5163. # Current object
  5164. try:
  5165. self.collection.get_active().read_form()
  5166. except:
  5167. self.log.debug("[warning] There was no active object")
  5168. pass
  5169. # Project options
  5170. self.options_read_form()
  5171. # Serialize the whole project
  5172. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  5173. "options": self.options,
  5174. "version": self.version}
  5175. # Open file
  5176. try:
  5177. f = open(filename, 'w')
  5178. except IOError:
  5179. App.log.error("[error] Failed to open file for saving: %s", filename)
  5180. return
  5181. # Write
  5182. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  5183. f.close()
  5184. # verification of the saved project
  5185. # Open and parse
  5186. try:
  5187. saved_f = open(filename, 'r')
  5188. except IOError:
  5189. self.inform.emit("[error_notcl] Failed to verify project file: %s. Retry to save it." % filename)
  5190. return
  5191. try:
  5192. saved_d = json.load(saved_f, object_hook=dict2obj)
  5193. except:
  5194. self.inform.emit("[error_notcl] Failed to parse saved project file: %s. Retry to save it." % filename)
  5195. f.close()
  5196. return
  5197. saved_f.close()
  5198. if 'version' in saved_d:
  5199. self.inform.emit("[success] Project saved to: %s" % filename)
  5200. else:
  5201. self.inform.emit("[error_notcl] Failed to save project file: %s. Retry to save it." % filename)
  5202. def on_options_app2project(self):
  5203. """
  5204. Callback for Options->Transfer Options->App=>Project. Copies options
  5205. from application defaults to project defaults.
  5206. :return: None
  5207. """
  5208. self.report_usage("on_options_app2project")
  5209. self.defaults_read_form()
  5210. self.options.update(self.defaults)
  5211. self.options_write_form()
  5212. def on_options_project2app(self):
  5213. """
  5214. Callback for Options->Transfer Options->Project=>App. Copies options
  5215. from project defaults to application defaults.
  5216. :return: None
  5217. """
  5218. self.report_usage("on_options_project2app")
  5219. self.options_read_form()
  5220. self.defaults.update(self.options)
  5221. self.defaults_write_form()
  5222. def on_options_project2object(self):
  5223. """
  5224. Callback for Options->Transfer Options->Project=>Object. Copies options
  5225. from project defaults to the currently selected object.
  5226. :return: None
  5227. """
  5228. self.report_usage("on_options_project2object")
  5229. self.options_read_form()
  5230. obj = self.collection.get_active()
  5231. if obj is None:
  5232. self.inform.emit("WARNING: No object selected.")
  5233. return
  5234. for option in self.options:
  5235. if option.find(obj.kind + "_") == 0:
  5236. oname = option[len(obj.kind) + 1:]
  5237. obj.options[oname] = self.options[option]
  5238. obj.to_form() # Update UI
  5239. def on_options_object2project(self):
  5240. """
  5241. Callback for Options->Transfer Options->Object=>Project. Copies options
  5242. from the currently selected object to project defaults.
  5243. :return: None
  5244. """
  5245. self.report_usage("on_options_object2project")
  5246. obj = self.collection.get_active()
  5247. if obj is None:
  5248. self.inform.emit("WARNING: No object selected.")
  5249. return
  5250. obj.read_form()
  5251. for option in obj.options:
  5252. if option in ['name']: # TODO: Handle this better...
  5253. continue
  5254. self.options[obj.kind + "_" + option] = obj.options[option]
  5255. self.options_write_form()
  5256. def on_options_object2app(self):
  5257. """
  5258. Callback for Options->Transfer Options->Object=>App. Copies options
  5259. from the currently selected object to application defaults.
  5260. :return: None
  5261. """
  5262. self.report_usage("on_options_object2app")
  5263. obj = self.collection.get_active()
  5264. if obj is None:
  5265. self.inform.emit("WARNING: No object selected.")
  5266. return
  5267. obj.read_form()
  5268. for option in obj.options:
  5269. if option in ['name']: # TODO: Handle this better...
  5270. continue
  5271. self.defaults[obj.kind + "_" + option] = obj.options[option]
  5272. self.defaults_write_form()
  5273. def on_options_app2object(self):
  5274. """
  5275. Callback for Options->Transfer Options->App=>Object. Copies options
  5276. from application defaults to the currently selected object.
  5277. :return: None
  5278. """
  5279. self.report_usage("on_options_app2object")
  5280. self.defaults_read_form()
  5281. obj = self.collection.get_active()
  5282. if obj is None:
  5283. self.inform.emit("WARNING: No object selected.")
  5284. return
  5285. for option in self.defaults:
  5286. if option.find(obj.kind + "_") == 0:
  5287. oname = option[len(obj.kind) + 1:]
  5288. obj.options[oname] = self.defaults[option]
  5289. obj.to_form() # Update UI
  5290. # end of file