FlatCAMApp.py 284 KB

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